Rust Const Generics Cheat Sheet
Parameterizing types and functions over compile-time constant values, array-length generics, and const expressions in bounds.
1 PageAdvancedFeb 24, 2026
Basic Const Generics
Parameterize a type over a compile-time constant, most commonly an array length.
rust
struct Matrix<const R: usize, const C: usize> { data: [[f64; C]; R],}impl<const R: usize, const C: usize> Matrix<R, C> { fn zero() -> Self { Matrix { data: [[0.0; C]; R] } } fn rows(&self) -> usize { R }}let m: Matrix<3, 4> = Matrix::zero(); // R=3, C=4 fixed at compile time
Generic Functions Over Array Length
Write one function that works for any array size N.
rust
fn sum<const N: usize>(arr: [i32; N]) -> i32 { arr.iter().sum()}let total = sum([1, 2, 3]); // N inferred as 3let total2 = sum([1, 2, 3, 4, 5]); // N inferred as 5// Const generics also work with referencesfn first_n<const N: usize>(slice: &[i32]) -> Option<[i32; N]> { slice.get(..N)?.try_into().ok()}
Const Params in Trait Bounds & Defaults
Const generics can have defaults and interact with where clauses.
rust
struct Buffer<const SIZE: usize = 1024> { data: [u8; SIZE],}let default_buf: Buffer = Buffer { data: [0; 1024] }; // uses default SIZElet small_buf: Buffer<64> = Buffer { data: [0; 64] };// Const expressions in bounds (stabilized incrementally, check MSRV)fn double_buf<const N: usize>() -> [u8; N * 2]where [(); N * 2]:,{ [0; N * 2]}
What's Stable vs. Still Limited
Const generics are powerful but arithmetic-in-types support is incremental.
- const N: usize params- fully stable for structs, enums, functions, impls
- array [T; N]- the most common use case, stable
- min_const_generics- the stabilized baseline feature (Rust 1.51+)
- const expressions (N + 1)- generic_const_exprs still nightly-only / unstable as of 2026
- const generics with traits- e.g. impl<const N: usize> Trait for [T; N], works for fixed small N via std
Pro Tip
When you hit 'generic parameters may not be used in const operations', it usually means you need the still-unstable generic_const_exprs feature — restructure to pass the derived constant explicitly as its own const generic parameter instead of computing it in-type.
Was this cheat sheet helpful?
Explore Topics
#RustConstGenerics#RustConstGenericsCheatSheet#Programming#Advanced#BasicConstGenerics#Generic#Functions#Over#DataStructures#CheatSheet#SkillVeris