Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 132 ยท Generics

Const Generics

Learn Rust const generics: code over any [T; N], a Matrix<R, C> with compile-time shape checks, const fn, braces, defaults and stable limits.

So far the generic parameters in this chapter have been types: T, K, V. But some facts about a program are not types at all. They are numbers. An array [i32; 4] is a different type from [i32; 5], because the length is part of the type. A 3x2 matrix is not a 2x3 matrix. A buffer that holds exactly 16 bytes is not a buffer that holds 32.

Const generics let you abstract over such values. A const parameter is written const N: usize and can be used in types ([T; N]) and in expressions (N * 2). Const generics have been stable for integers, bool and char since Rust 1.51 (March 2021), and the standard library now relies on them: arrays implement traits such as Debug, PartialEq and Default for every length, not just the first 32 as before. This lesson builds on arrays and generics.

Generic over the array length

Before const generics, you could not write one function that accepted [i32; 3] and [i32; 7]. You can now, by declaring the length as a parameter.

Rust A function over any array length

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

N can be read like a constant inside the function ( in the format string works). The compiler infers it from the argument, just as it infers T. Notice that sum_array([]) works too: the empty array has N = 0. Each distinct N produces its own compiled copy, exactly like type parameters do under monomorphization.

Why would you prefer [i32; N] over a slice &[i32]? A slice has its length only at run time. An array parameter has it at compile time, which lets the compiler remove bounds checks, unroll loops, and, more importantly, lets types say that two things have the same size.

Rust Types that say two arrays are the same length

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Both parameters share the same N, so passing arrays of different lengths is a compile error rather than a run-time panic or a silent truncation. std::array::from_fn builds an array of length N by calling a closure with each index; it is a common companion to const generics.

Rust Mismatched array lengths (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The result is error[E0308]: mismatched types, with the note that it expected an array with a size of 3 but found one with a size of 2. This kind of bug is exactly what the type system is for.

Const parameters on structs and impls

Like type parameters, const parameters can sit on structs. A fixed-capacity stack that lives entirely on the stack (no heap allocation) is a typical use.

Rust A fixed-capacity stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Stack<char, 3> and Stack<char, 4> are different types of different sizes, with no Vec and no allocation. This pattern is popular in embedded Rust, where there is no heap. The T: Copy bound lets [None; CAP] repeat the value None, which requires it to be Copy (or a const).

Array wrappers and the traits they get

A wrapper around an array can implement traits for all lengths in a single impl.

Rust A wrapper type with Display and Index for every length

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The standard library is built the same way. [T; N] implements Default, Debug, Clone, PartialEq, Hash and others for all N, provided T does. The array::map method used above and TryFrom<&[T]> for [T; N], shown next, are everyday tools.

Slices to arrays

Converting a slice (length known only at run time) into an array (length in the type) can fail, so it uses TryFrom.

Rust From a slice to a fixed array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The unwrap is safe here only because chunks_exact(3) guarantees the chunk length; with arbitrary slices, handle the Err.

A Matrix that checks its own shape

Matrix multiplication is the showpiece. An R x K matrix times a K x C matrix gives an R x C matrix, and the inner dimension K must agree. With const generics, the compiler verifies that.

Rust Matrix with const row and column counts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Look at the signature of mul: the left matrix is R x K, the right one is K x C, and the output is R x C. The same letter K on both sides means the inner dimensions must match. Trying product * a multiplies a 2x2 by a 2x3, which is fine, but a * a is a 2x3 by a 2x3, and the compiler rejects it.

Rust Multiplying incompatible shapes (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports error[E0308]: mismatched types with the label "expected 3, found 2" and the note that it expected Matrix<3, _> but found Matrix<2, 3>: the right operand must have three rows, and it has two. A shape bug that would be a run-time panic in most languages never reaches the user.

Const arguments: values, braces and defaults

When you write a const argument, plain literals and bare const parameters are fine: Stack<char, 3>, Matrix<R, C>. Anything more complicated needs braces, which mark an expression: Stack<u8, { 4 * 4 }>. Const parameters may also have defaults, and they may be bool or char as well as integers.

Rust Braces, defaults and non-integer const parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Giving each Flag<true> and Flag<false> a different type is the idea behind several type-state designs; see Type-state and builder patterns. Types for const parameters are limited to the integer types, bool and char. Strings, floats and your own structs are not allowed on stable Rust.

const fn: computing at compile time

A const fn is a function that the compiler is allowed to run during compilation. It can be called in a normal program as well, but it can also be used where a constant is required, such as in an array length, a const item, a static, or a const argument.

Rust const fn feeding a const parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

const fn bodies are limited. Loops are written with while (a for loop needs the Iterator trait, which is not usable in const code on stable Rust), and the function may only call other const fns. Many standard methods are const, including len(), leading_zeros(), min on integers and Vec::new(). When you want a lookup table, building it in a const or static initialiser means zero work at program start.

Limits: no arithmetic on const parameters in types

The most surprising restriction: you can use N in an expression, but you cannot compute a type from it. [T; N + 1] and Matrix<{ R * C }, 1> need an unstable feature (generic_const_exprs) and do not compile on stable Rust.

Rust Arithmetic inside a type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You get error: generic parameters may not be used in const operations, with the label "cannot perform const operation using N" and the help "const parameters may only be used as standalone arguments here, i.e. N". It is reported twice here, once for the return type and once for the array inside the body. The usual workarounds are to take the output length as a second parameter (fn grow<const N: usize, const M: usize>(...) -> [i32; M] and check M == N + 1 with an assert! or a const assertion), to return a Vec when the size is truly dynamic, or to accept that the feature is not yet available. A compile-time assertion inside an associated const is a common stand-in:

Rust
struct NonEmpty<const N: usize>;

impl<const N: usize> NonEmpty<N> {
    const CHECK: () = assert!(N > 0, "N must be at least 1");

    fn new() -> Self {
        let () = Self::CHECK; // evaluating the const triggers the assertion
        NonEmpty
    }
}

If you call NonEmpty::<0>::new(), the build fails with error[E0080]: evaluation panicked: N must be at least 1, pointing at your assertion and at the NonEmpty::<0>::new() call that instantiated it. That turns a rule about the parameter into a compile-time error.

When to use const generics

Use them when a number is part of what a thing is: fixed-size buffers, matrices, vectors in a given dimension, bit sets, hash digests, and ring buffers on embedded targets. They give you stack allocation, shape-checked APIs and removal of bounds checks. Avoid them when the size is naturally dynamic (use Vec or a slice), when the parameter would take dozens of different values in one program (each value is a separate compiled copy, so compile time and binary size grow), and when you only want to pass an array around (a &[T] slice is simpler and does not instantiate a new function per length).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fn f<const N: usize>(a: [u8; N]) allow?

    N is a const generic parameter inferred from the argument's type. Each length gets its own compiled copy of the function.
  2. 2. Which types can be used for a const generic parameter on stable Rust?

    Const parameters are limited to the integer types, bool and char. Strings, floats and structs are not allowed.
  3. 3. Why does Matrix<2, 3> * Matrix<2, 3> fail to compile with the Mul impl in this lesson?

    impl Mul<Matrix<K, C>> for Matrix<R, K> uses K twice, so the left matrix's column count must equal the right matrix's row count.
  4. 4. Which of these does NOT compile on stable Rust?

    Using arithmetic on a const parameter inside a type needs the unstable generic_const_exprs feature. You get generic parameters may not be used in const operations.
  5. 5. What is a const fn?

    A const fn can be used in constant contexts such as array lengths, const items and const generic arguments, and also called normally at run time.

Summary

  • Const generics let you parameterise code by a value: const N: usize, usable in types ([T; N]) and expressions.
  • Allowed parameter types are integers, bool and char; arguments that are not a plain literal or parameter need braces, as in Buffer::<{ 4 * 4 }>.
  • Sharing one N between parameters turns length mismatches into compile errors, as in dot and in Matrix<R, K> * Matrix<K, C>.
  • Each distinct value is its own instantiation: allocation-free types like Stack<T, CAP>, but more compiled code.
  • const fn runs at compile time and can compute array lengths, const items, static tables and const arguments.
  • Arithmetic on a const parameter inside a type ([T; N + 1]) is not stable; use extra parameters, assertions in associated consts, or a Vec.

Next: Advanced Traits: Supertraits, Newtype and Disambiguation