rust / intermediate
Snippet
Const Generics: Compile-Time Array Dimensions
Const generics allow you to use constants as type parameters, enabling compile-time parameterized types. Unlike C++ templates with non-type parameters, Rust validates all const generic bounds at compile time. This is particularly powerful for zero-cost abstractions in array handling, avoiding heap allocations and enabling the compiler to fully optimize the code. The Matrix example demonstrates how to create a generic fixed-size 2D array structure where dimensions are part of the type signature, making it impossible to create mismatched matrix operations at compile time.
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
use std::fmt::Display;struct Matrix<T, const ROWS: usize, const COLS: usize> {data: [[T; COLS]; ROWS],}impl<T: Default + Copy, const ROWS: usize, const COLS: usize> Matrix<T, ROWS, COLS> {fn new() -> Self {Self { data: [[T::default(); COLS]; ROWS] }}fn get(&self, row: usize, col: usize) -> Option<&T> {if row < ROWS && col < COLS {Some(&self.data[row][col])} else {None}}}fn main() {let mat: Matrix<i32, 3, 4> = Matrix::new();println!("{:?}", mat.get(1, 2));}
Breakdown
1
struct Matrix<T, const ROWS: usize, const COLS: usize>
Generic struct with two const generic parameters for dimensions
2
data: [[T; COLS]; ROWS]
Nested array type: array of ROWS elements, each being [T; COLS]
3
fn get(&self, row: usize, col: usize) -> Option<&T>
Bounds-checked accessor returning Option to handle invalid indices safely