Sub topic 15
Writing code generic over array length
This chapter assumes you know that [T; N] is an array type, that &[T] is a slice, and how generic type parameters like T work.
The problem: the length is part of the type
In Rust, [i32; 2] and [i32; 3] are different types. A function that takes [i32; 3] rejects every other length. Slices avoid this when you only need to read elements, but sometimes you need the length in the type. You may want to return an array, or require that two arrays have equal lengths.
Const generic parameters
A const generic parameter is a generic parameter that holds a value instead of a type. You declare it with const and give it a type, usually usize:
fn sum_all<const N: usize>(values: [i32; N]) -> i32 {
values.iter().sum()
}
fn main() {
println!("{}", sum_all([1, 2, 3]));
println!("{}", sum_all([1, 2, 3, 4, 5]));
}The compiler infers N from the argument. The first call uses N = 3 and the second uses N = 5. Inside the function, N is a compile-time constant. You can use it in expressions such as 0..N or in other array types such as [u8; N].
Returning an array of a chosen length
Const generics are most useful when the caller picks the length. The function below returns the first N elements as an array:
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 too_long: Option<[i32; 8]> = first_n(&data);
println!("{:?}", too_long);
}This prints Some([10, 20]) and then None. The function works in three steps:
values.get(..N)returnsNoneif the slice has fewer thanNelements. The?returns thatNoneearly.- Otherwise it returns a slice of exactly
Nelements.try_into()converts that slice to[i32; N]. The conversion is fallible because the compiler cannot see the slice's length. .ok()turns theResultinto theOptionthe signature promises.
The caller chooses N through the type annotation. You can also write it explicitly with the turbofish: first_n::<2>(&data).
Common errors
- Using a runtime value as
N.first_n::<n>(&data)fails whennis aletvariable. Only constants, literals, and const items are allowed. For lengths known only at run time, use aVec. - Annotation missing. If nothing fixes
N, the compiler reports that it cannot infer the value. Add a type annotation or a turbofish. - Array expressions with
N. Stable Rust does not accept arithmetic onNinside a type, such as[i32; N + 1]. KeepNplain in types. - Large
Non the stack. Arrays live inline, so a very largeNcan overflow the stack.
Exercise
In the first_n example above, what does first_n::<4>(&[1, 2, 3]) return, and why?
Show answer
It returns None. The slice has 3 elements, so get(..4) returns None and the ? operator returns that None before try_into runs.