generic

Rust Const generics

A const parameter represents a compile-time value. It can describe fixed-size data such as an array whose length belongs to the type, rather than a runtime field. Expected output (not executed): 3 Why: The array length determines N as 3. Buffer<3> and Buffer<4> differ in type. Common mistake: Passing an ordinary runtime variable as a const argument.

Formal Syntax & Structure

rust syntaxrust
struct Buffer<const N: usize>([u8; N]);

Working Example

Example Snippetrust
struct Buffer<const N: usize>([u8; N]);fn main() {    let buffer = Buffer([3, 5, 7]);    println!("{}", buffer.0.len());}
Rust Reference