Const generics
Quick answer
Const generics allow values such as array lengths to be part of a generic type or function. Use them when size is known at compile time and should be checked by the type system.
Represent length in the type
const N: usize introduces a compile-time length parameter. [T; N] uses it directly. The stable baseline supports standalone const parameters in array lengths, but arbitrary arithmetic on generic const parameters in types is restricted. A runtime variable cannot be substituted as a const argument.
fn sum<const N: usize>(a: [i32; N]) -> i32 { a.iter().sum() }fn main() { println!("{} {}", sum([1, 2]), sum([1, 2, 3])); }Expected stdout (not executed):
3 6The compiler infers a different N for each call.
fn same<const N: usize>(_: [u8; N], _: [u8; N]) {}fn main() { same([0; 2], [0; 3]); }Expected: compilation fails; exact diagnostic not verified.
Both parameters must agree on N.
Common mistake
Do not use a const generic when the length is only known at runtime; a slice is often better.
Try it yourself
Write a function taking two arrays of equal length and returning their element-wise sums using std::array::from_fn.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Const generics — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
Two arrays passed to a function must have identical compile-time lengths. Which signature concept fits?
Const generics — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn sum<const N: usize>(a: [i32; N]) -> i32 { a.iter().sum() } fn main() { println!("{} {}", sum([1, 2]), sum([1, 2, 3])); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Const generics — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn same<const N: usize>(_: [u8; N], _: [u8; N]) {} fn main() { same([0; 2], [0; 3]); } ``` Which outcome or interpretation best matches this example?