rust / expert
Snippet
Overloading Indexing Operators for Two-Dimensional Array Strides
Utilizing the Index and IndexMut traits allows custom structures representing arrays to support standard bracket notation. By mapping a 2D coordinate (row, col) to a 1D flat buffer using a compile-time checked stride dimension (WIDTH), we achieve safety and clean ergonomics.
snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use std::ops::{Index, IndexMut};pub struct FlattenedGrid<T, const WIDTH: usize> {pub buffer: Vec<T>,}impl<T, const WIDTH: usize> Index<(usize, usize)> for FlattenedGrid<T, WIDTH> {type Output = T;fn index(&self, index: (usize, usize)) -> &Self::Output {let (row, col) = index;&self.buffer[row * WIDTH + col]}}impl<T, const WIDTH: usize> IndexMut<(usize, usize)> for FlattenedGrid<T, WIDTH> {fn index_mut(&mut self, index: (usize, usize)) -> &mut Self::Output {let (row, col) = index;&mut self.buffer[row * WIDTH + col]}}
Breakdown
1
impl<T, const WIDTH: usize> Index<(usize, usize)> for FlattenedGrid<T, WIDTH> {
Allows indexing with coordinates of type (usize, usize) by overloading the index operator.
2
&self.buffer[row * WIDTH + col]
Translates 2D indexing into 1D indexing based on the compile-time width value, returning a reference to the element.
3
impl<T, const WIDTH: usize> IndexMut<(usize, usize)> for FlattenedGrid<T, WIDTH> {
Implements the mutable variant of index operator overloading, allowing direct assignment to mapped elements.