rust / expert
Snippet
Enforcing Array Dimension Boundaries at Compile-Time via Const Generics
Demonstrates compile-time validation of mathematical dimensions using const generics. Incorrect matrix multiplications will fail to compile, eliminating runtime boundary checks.
snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
pub struct Matrix<const ROWS: usize, const COLS: usize> {pub data: [[f64; COLS]; ROWS],}impl<const ROWS: usize, const COLS: usize> Matrix<ROWS, COLS> {pub fn multiply<const OTHER_COLS: usize>(&self,other: &Matrix<COLS, OTHER_COLS>) -> Matrix<ROWS, OTHER_COLS> {let mut result_data = [[0.0; OTHER_COLS]; ROWS];for r in 0..ROWS {for c in 0..OTHER_COLS {let mut sum = 0.0;for i in 0..COLS {sum += self.data[r][i] * other.data[i][c];}result_data[r][c] = sum;}}Matrix { data: result_data }}}
Breakdown
1
pub struct Matrix<const ROWS: usize, const COLS: usize> {
Declares a generic matrix structure parameterized by compile-time integers.
2
other: &Matrix<COLS, OTHER_COLS>
Enforces that the column count of the first matrix matches the row count of the second.
3
-> Matrix<ROWS, OTHER_COLS> {
Calculates and returns the exact resultant dimensions validated by the type system.
4
let mut result_data = [[0.0; OTHER_COLS]; ROWS];
Initializes the output buffer dynamically allocated in stack frames based on const parameters.