Sub topic 15
Writing code generic over array length
This chapter assumes you know that an array type [T; N] includes its length, that slices (&[T]) borrow a view of an array, and that functions can take type parameters such as <T>. Const generics let a function or type take the length N as a parameter, the way Vec<T> takes T.
Why the length is a type-level value
In Rust, [i32; 3] and [i32; 4] are different types. Before const generics, a function that took [i32; 3] could not also take [i32; 4]. The usual fix was to accept &[i32], which loses the length at compile time.
A const generic parameter keeps the length in the type system. You write const N: usize in the angle brackets, then use N in types and in ordinary expressions.
fn sum_all<const N: usize>(values: [i32; N]) -> i32 {
println!("summing {N} values");
values.iter().sum()
}
fn main() {
println!("{}", sum_all([1, 2, 3]));
println!("{}", sum_all([10, 20, 30, 40, 50]));
}The compiler infers N from the argument. Inside the function, N is a usize constant you can print, compare, or use as a loop bound.
Combining type and const parameters
Type parameters and const parameters can appear together. By convention, lifetimes come first, then types, then consts, though the compiler accepts consts mixed with types.
fn largest<T: PartialOrd + Copy, const N: usize>(items: [T; N]) -> Option<T> {
let mut iter = items.into_iter();
let mut best = iter.next()?;
for v in iter {
if v > best {
best = v;
}
}
Some(best)
}
fn main() {
println!("{:?}", largest([3, 9, 2]));
println!("{:?}", largest([1.5, 0.5]));
println!("{:?}", largest::<char, 0>([]));
}When N is zero, next() returns None, so the ? operator returns None early. That is why the return type is Option<T>. The last call uses a turbofish (::<char, 0>) because an empty array literal gives the compiler nothing to infer T from.
Choosing the length at the call site
A function can also pick the length from the return type. The first_n function below copies the first N items of a slice into an array. It returns None if the slice is too short.
fn first_n<const N: usize>(values: &[i32]) -> Option<[i32; N]> {
values.get(..N)?.try_into().ok()
}
fn main() {
let data = [10, 20, 30, 40];
let head: Option<[i32; 2]> = first_n(&data);
println!("{:?}", head);
let explicit = first_n::<3>(&data);
println!("{:?}", explicit);
let too_long: Option<[i32; 8]> = first_n(&data);
println!("{:?}", too_long);
}There are two ways to supply N: annotate the result type, or write first_n::<3>. The try_into call turns a &[i32] into [i32; N] and fails when the lengths differ. Here get(..N) already guarantees the length, so ok() always succeeds on that path. This conversion needs T: Copy, which i32 satisfies.
Const parameters on structs
Structs and impl blocks take const parameters too. The type of a matrix can then record its dimensions, so the compiler rejects mismatched operations.
#[derive(Debug)]
struct Matrix<const R: usize, const C: usize> {
data: [[i32; C]; R],
}
impl<const R: usize, const C: usize> Matrix<R, C> {
fn transpose(&self) -> Matrix<C, R> {
let mut data = [[0; R]; C];
for r in 0..R {
for c in 0..C {
data[c][r] = self.data[r][c];
}
}
Matrix { data }
}
}
fn main() {
let m = Matrix { data: [[1, 2, 3], [4, 5, 6]] };
let t = m.transpose();
println!("{:?}", t);
}m is a Matrix<2, 3> and t is a Matrix<3, 2>. Swapping R and C in the return type is all it takes. A function that expects Matrix<3, 2> will not accept m, and the error appears at compile time.
How the compiler handles it
Rust generates a separate copy of the function for each distinct N you use. This is monomorphization, the same process used for type parameters. sum_all::<3> and sum_all::<5> become two functions, and each can have its loop unrolled or bounds checks removed for its fixed length.
The cost is code size. If you call a generic function with many different lengths, you get many copies.
Common errors
The following restrictions affect stable Rust.
- Allowed types. A const parameter can be an integer type,
bool, orchar. Strings, floats, and structs are not allowed. - No arithmetic on
Nin types. Writing[T; N * 2]or[T; N + 1]inside a generic function is rejected on stable Rust. That needs the unstablegeneric_const_exprsfeature. Pass a second const parameter or use aVecinstead. - Values must be known at compile time.
first_n::<n>fails ifnis a runtime variable. Use a slice when the length is only known at runtime. - Braces for expressions. A literal or a bare const name can be used directly. Any other expression needs braces, as in
first_n::<{ 2 + 1 }>. - Inference failure. If nothing fixes
N, as with an empty[]or an unannotatedfirst_n(&data), the compiler reports that it cannot infer the const parameter. Annotate the type or use a turbofish.
Const generics or slices
Prefer a slice parameter unless the length matters to the type. A &[T] function is compiled once and accepts arrays, Vecs, and sub-ranges.
| Need | Use |
|---|---|
| Read or process any number of items | `&[T]` |
| Require callers to pass exactly N items | `[T; N]` or `&[T; N]` |
| Return an array whose length the caller chooses | `const N: usize` |
| Relate two lengths, such as matrix dimensions | Several const parameters |
| Length known only at runtime | `Vec<T>` or a slice |
Exercise
What do first_n::<8>(&[10, 20, 30, 40]) and first_n::<0>(&[10, 20, 30, 40]) return, and why?
Show answer
The first returns None, because get(..8) on a four-element slice yields None and the ? operator returns early. The second returns Some([]). get(..0) gives an empty slice, and converting it to [i32; 0] succeeds because the lengths match.
Exercise
Why does fn double<const N: usize>(a: [i32; N]) -> [i32; N * 2] fail to compile on stable Rust, and how would you change the signature to work?
Show answer
Stable Rust does not allow arithmetic on a const parameter inside a type. Add a second parameter, such as fn double<const N: usize, const M: usize>(a: [i32; N]) -> [i32; M], and have the caller supply M. Alternatively, return a Vec<i32>.