Sub topic 13
Const generics
This chapter assumes you can write generic functions and structs with type parameters, use trait bounds, and read basic array types such as [i32; 3].
What a const parameter is
A type parameter stands for a type. A const generic parameter stands for a value that is known at compile time. The most common use is an array length.
Without const generics, a function over arrays needs one version per length, or it must take a slice and lose the length from the type. A const parameter lets one function handle arrays of any size while keeping the size in the 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 declaration const N: usize goes in the same angle brackets as type parameters. The compiler infers N from the argument. The first call uses N = 3 and the second uses N = 5. The output is 6 and 50.
Sizes are part of the type
Because N is part of the type, [i32; 3] and [i32; 4] are different types. Using the same N twice makes the compiler check that the lengths match:
fn dot<const N: usize>(a: [i32; N], b: [i32; N]) -> i32 {
a.iter().zip(b.iter()).map(|(x, y)| x * y).sum()
}
fn main() {
println!("{}", dot([1, 2, 3], [4, 5, 6]));
// dot([1, 2, 3], [4, 5]); // error: mismatched types, expected an array with a size of 3
}The length mismatch is a compile error, so no runtime check is needed. A slice-based version would need a runtime check, or it would silently ignore extra elements.
Const parameters on structs
Const parameters can be combined with type parameters. The type parameters conventionally come first. Lifetimes come before both.
struct Buffer<T, const N: usize> {
data: [T; N],
}
impl<T: Copy + Default, const N: usize> Buffer<T, N> {
fn new() -> Self {
Buffer { data: [T::default(); N] }
}
fn capacity(&self) -> usize {
N
}
fn first(&self) -> Option<&T> {
self.data.first()
}
}
fn main() {
let b: Buffer<u8, 4> = Buffer::new();
println!("{} {:?}", b.capacity(), b.first());
}Inside the impl, N works as a normal usize value, as in capacity. The program prints 4 Some(0). The buffer lives on the stack, with no heap allocation and no stored length field.
When inference cannot work out the value, supply it explicitly with the turbofish. For example, sum::<3>([1, 2, 3]) sets N to 3. A literal needs no braces. A computed value does, as in Buffer::<u8, { 2 + 2 }>::new().
How it compiles
Const generics are monomorphized like type parameters. The compiler generates a separate copy of the code for each distinct value of N that you use.
This lets the compiler unroll loops and drop bounds checks for known sizes. The cost is the same as for type parameters: more distinct sizes mean more generated code.
Limits and common errors
- Stable Rust allows only integer types,
bool, andcharas const parameter types. You cannot useStringor a&str. - Arithmetic on a parameter inside a type is not allowed on stable Rust. A signature like
fn f<const N: usize>() -> [u8; N + 1]fails to compile. Use a separate parameter, or a slice. - Standard library arrays already use const generics. Methods such as
mapon[T; N]work for every length. [T::default(); N]needsT: Copy. IfTis notCopy, usestd::array::from_fninstead.
Exercise
Why does dot([1, 2, 3], [4, 5]) fail to compile when dot is declared as fn dot<const N: usize>(a: [i32; N], b: [i32; N]) -> i32?
Show answer
Both parameters use the same N. The first argument fixes N = 3, but the second argument has type [i32; 2], which would need N = 2. One parameter cannot be both, so the compiler reports a type mismatch.