Sub topic 13
Const generics
Const generics let a type or function take a value as a parameter, usually a number such as an array length. The compiler checks that value at compile time, the same way it checks a type parameter. This chapter assumes you have read the earlier chapters of this tutorial. You should be comfortable with generic functions, impl<T> blocks, and trait bounds. You should also know that Rust arrays have the type [T; N], where N is part of the type.
The problem const generics solve
The type [i32; 3] is different from [i32; 4]. Before Rust 1.51, the standard library could only implement traits for arrays up to length 32, because each length needed its own impl. Const generics fixed this. A single declaration can now be generic over the length, and the length is checked like any other part of the type.
A const parameter is declared with the const keyword, a name, and a type:
fn sum<const N: usize>(values: [i32; N]) -> i32 {
values.iter().sum()
}
fn main() {
println!("{}", sum([1, 2, 3]));
println!("{}", sum([10; 5]));
}The program prints 6 and 50. The compiler infers N from the argument, as it does for T. The first call uses N = 3 and the second uses N = 5. Inside the body, N is a normal usize value. You can use it in expressions such as for i in 0..N, and in types such as [0u8; N].
You can also pass the value explicitly with a turbofish:
fn take<T: Copy, const N: usize>(items: &[T]) -> Option<[T; N]> {
items.get(..N)?.try_into().ok()
}
fn main() {
let v = [1, 2, 3];
println!("{:?}", take::<_, 2>(&v));
println!("{:?}", take::<i32, 4>(&v));
let pair: Option<[i32; 2]> = take(&v);
println!("{:?}", pair);
}This prints Some([1, 2]), None, and Some([1, 2]). The function turns a slice into an array whose length is chosen by the caller. The slice only has a length at run time, so the conversion returns Option. The length of the result is still part of the type. In the last call, the annotation on pair lets the compiler infer N = 2 with no turbofish.
Where const arguments can come from
On stable Rust, the argument for a const parameter must be one of these:
- A literal, such as
3ortrue. - Another const parameter, such as
N, passed through. - A block
{ ... }containing a constant expression that does not mention any generic parameters, such as{ 2 + 3 }.
An expression without braces is not accepted in an argument position, so you write Foo::<{ 2 + 3 }>. The braces cannot contain generic parameters. That is why [T; N + 1] and Matrix<{ R * C }> do not compile today. Arithmetic on const parameters inside types needs the unstable generic_const_exprs feature.
The type of a const parameter is also restricted on stable Rust. It must be an integer type (u8 through u128, i8 through i128, usize, isize), bool, or char. Floats, &str, and your own enums and structs are not allowed.
Generic structs with const parameters
A struct can carry a length in its type. Here the shape of a matrix is part of the type:
#[derive(Debug, Clone, Copy, PartialEq)]
struct Matrix<const R: usize, const C: usize> {
data: [[i32; C]; R],
}
impl<const R: usize, const C: usize> Matrix<R, C> {
fn new(data: [[i32; C]; R]) -> Self {
Matrix { data }
}
fn transpose(&self) -> Matrix<C, R> {
let mut out = [[0; R]; C];
for r in 0..R {
for c in 0..C {
out[c][r] = self.data[r][c];
}
}
Matrix { data: out }
}
fn mul<const K: usize>(&self, other: &Matrix<C, K>) -> Matrix<R, K> {
let mut out = [[0; K]; R];
for r in 0..R {
for k in 0..K {
for c in 0..C {
out[r][k] += self.data[r][c] * other.data[c][k];
}
}
}
Matrix { data: out }
}
}
fn main() {
let m = Matrix::new([[1, 2, 3], [4, 5, 6]]);
let t = m.transpose();
println!("{:?}", t);
println!("{:?}", m.mul(&t));
}The output is:
Matrix { data: [[1, 4], [2, 5], [3, 6]] }
Matrix { data: [[14, 32], [32, 77]] }Look at the signature of mul. The other matrix must have C rows, which is this matrix's column count. The result has R rows and K columns. Multiplying a 2×3 matrix by another 2×3 matrix is a compile error, with a mismatched types message that names the two shapes. A shape bug becomes a type error instead of an out-of-bounds panic at run time.
The derive attributes work because the standard library implements Debug, Clone, Copy and PartialEq for arrays of every length.
Specialized impls
The specialized impls from the earlier chapter work with const parameters too. You can write an impl that exists only when two parameters are equal:
struct Matrix<const R: usize, const C: usize> {
data: [[i32; C]; R],
}
impl<const N: usize> Matrix<N, N> {
fn trace(&self) -> i32 {
(0..N).map(|i| self.data[i][i]).sum()
}
}
fn main() {
let square = Matrix { data: [[1, 2], [3, 4]] };
println!("{}", square.trace());
}This prints 5. Calling trace on a 2×3 matrix is a compile error, because no Matrix<2, 3> method named trace exists.
Default values
A const parameter can have a default, which is useful for sizes that are usually the same:
struct Stack<T, const CAP: usize = 4> {
items: [Option<T>; CAP],
len: usize,
}
impl<T, const CAP: usize> Stack<T, CAP> {
fn new() -> Self {
Stack {
items: std::array::from_fn(|_| None),
len: 0,
}
}
fn push(&mut self, value: T) -> Result<(), T> {
if self.len == CAP {
return Err(value);
}
self.items[self.len] = Some(value);
self.len += 1;
Ok(())
}
fn pop(&mut self) -> Option<T> {
if self.len == 0 {
return None;
}
self.len -= 1;
self.items[self.len].take()
}
}
fn main() {
let mut s: Stack<i32, 2> = Stack::new();
println!("{:?}", s.push(1));
println!("{:?}", s.push(2));
println!("{:?}", s.push(3));
println!("{:?}", s.pop());
let d: Stack<u8> = Stack::new();
println!("{}", d.items.len());
}The output is Ok(()), Ok(()), Err(3), Some(2), and 4. The stack stores its items inline in an array, so it never allocates on the heap. push hands the value back in Err when the stack is full.
The initializer std::array::from_fn(|_| None) is needed because [None; CAP] requires Option<T> to be Copy, and T has no such bound. Defaults only apply where the compiler reads a type annotation, as in Stack<u8>. They do not drive inference from expressions. This is the same rule as for type parameter defaults.
Compile-time checks on the parameter
Sometimes a value is valid as a usize but invalid for your code. A zero-length array is one example. You can reject it with an inline const block, which may use generic parameters. Inline const blocks require Rust 1.79 or later.
fn first<T: Copy, const N: usize>(items: [T; N]) -> T {
const { assert!(N > 0, "array must not be empty") };
items[0]
}
fn main() {
println!("{}", first([7, 8, 9]));
}This prints 7. The assertion is evaluated for each concrete N when the function is instantiated. Calling first::<i32, 0>([]) fails to build. Because the check runs after monomorphization, cargo check may not report it. A full cargo build does.
Choosing between const generics and slices
| Need | Prefer |
|---|---|
| Length read from a file or user input | `&[T]` or `Vec<T>` |
| Function that only reads elements | `&[T]` |
| Fixed-size buffer with no heap allocation | `[T; N]` with const generics |
| Shapes that must match, such as matrix multiplication | Const generic struct |
| Returning an array whose length the caller picks | `const N: usize` |
A function that takes &[T] works with arrays of every length and compiles once. A function generic over N gets a separate compiled copy for each length used, as described in the monomorphization chapter. Use const generics when the length carries meaning. Otherwise a slice costs less in code size.
Common errors
- Using an expression without braces.
Foo::<N + 1>does not parse as a const argument. Wrap constant expressions in braces, and note that braces cannot mention generic parameters. - Arithmetic in a type.
[i32; N * 2]inside a generic function fails on stable. Take the doubled length as a second parameter, or use a slice. - Unsupported parameter types.
const NAME: &strandconst X: f64are rejected. Use an integer,bool, orchar, or pass the value at run time. - Mismatched lengths.
[i32; 3]and[i32; 4]are different types, so a function with two[T; N]parameters rejects arguments of different lengths. This is often the point of the design. - Large arrays on the stack.
Stack<T, 1_000_000>places the array in the stack frame, which can overflow the stack. UseVecorBoxfor big buffers.
Exercise
Write the signature of a method append on Buffer<const N: usize> (which wraps [u8; N]) that joins it with a Buffer<M> and returns a Buffer<{ N + M }>. Will this compile on stable Rust? If not, what alternative keeps the length checked?
Show answer
The signature would be fn append<const M: usize>(self, other: Buffer<M>) -> Buffer<{ N + M }>. It does not compile on stable Rust, because a const argument in braces cannot use generic parameters like N and M. That needs the unstable generic_const_exprs feature. One alternative is to make the output length a third parameter, fn append<const M: usize, const T: usize>(self, other: Buffer<M>) -> Buffer<T>, and check N + M == T with an inline const { assert!(...) } block. A second alternative is to return a Vec<u8>, which gives up the length in the type.
Exercise
Why does impl<const N: usize> Matrix<N, N> let you call trace on a 2×2 matrix but not on a 2×3 matrix?
Show answer
The impl block applies only when both const arguments are the same value N. For Matrix<2, 2> the compiler finds N = 2. For Matrix<2, 3> no single N fits both positions, so the method does not exist for that type and the call is a compile error.