rust / intermediate
Snippet
Const Generics: Compile-Time Generics
Const generics allow types to be parameterized by constant values, not just types. This enables array-based data structures with compile-time known dimensions. The compiler can optimize better since array sizes are known at compile time, enabling stack allocation instead of heap.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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> {fn new(value: T) -> Selfwhere T: Default + Copy {Matrix { data: [[value; M]; N] }}fn get(&self, i: usize, j: usize) -> Option<&T> {if i < N && j < M {Some(&self.data[i][j])} else {None}}}fn smallest<T: PartialOrd + Copy, const N: usize>(arr: &[T; N]) -> T {let mut smallest = arr[0];let mut i = 1;while i < N {if arr[i] < smallest {smallest = arr[i];}i += 1;}smallest}fn main() {let m: Matrix<i32, 2, 3> = Matrix::new(0);if let Some(val) = m.get(1, 2) {println!("Value at [1,2]: {}", val);}let arr = [3, 1, 4, 1, 5];println!("Smallest: {}", smallest(&arr)); // 1}
Breakdown
1
const N: usize, const M: usize
Const generics parameters for matrix dimensions
2
[[T; M]; N]
2D array with N rows of M-element arrays
3
let arr = [3, 1, 4, 1, 5];
Compile-time array size used with const generic function
4
smallest(&arr)
Array size inferred and passed as compile-time constant