capypad
0 day streak
rust / intermediate
Snippet

Const Generics for Zero-Cost Abstraction

Const generics allow compile-time constants as generic parameters. Unlike type parameters that accept types, const parameters accept compile-time constant values like integer literals. This enables creating truly generic containers whose size is determined at compile time, with zero runtime overhead.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct Matrix<T, const N: usize, const M: usize> {
data: [[T; M]; N],
}
 
impl<T, const N: usize, const M: usize> Matrix<T, N, M>
where
T: Default + Copy,
{
fn new() -> Self {
Self { data: [[T::default(); M]; N] }
}
}
 
fn main() {
let m: Matrix<i32, 2, 3> = Matrix::new();
println!("Matrix size: {}x{}", 2, 3);
}
Breakdown
1
const N: usize, const M: usize
Declares const generic parameters N and M of type usize for dimensions
2
data: [[T; M]; N]
Creates a 2D array of type T with dimensions N x M, all known at compile time
3
where T: Default + Copy,
Requires T to be Default-constructible and Copy for stack-based storage
4
[[T::default(); M]; N]
Creates array by repeating default value M times for N rows
5
let m: Matrix<i32, 2, 3> = Matrix::new();
Creates a 2x3 matrix with specific compile-time dimensions