Index Trait For Grid Access

Implementing Index and IndexMut with tuple keys gives grid[x, y] syntax, while a get method keeps out-of-bounds decisions with the caller.

RustData Integrity

Code

rustsnippet
45 lines
use std::ops::{Index, IndexMut};

struct Grid<T> {
    width: usize,
    cells: Vec<T>,
}

impl<T> Grid<T> {
    fn new(width: usize, height: usize, fill: T) -> Self
    where
        T: Clone,
    {
        Grid { width, cells: vec![fill; width * height] }
    }

    // get 把越界决定权交还调用方:返回 Option 而不是 panic
    fn get(&self, x: usize, y: usize) -> Option<&T> {
        if x >= self.width {
            return None;
        }
        self.cells.get(y * self.width + x)
    }
}

// Index 让 grid[x, y] 下标语法成立:越界按 Vec 惯例 panic
impl<T> Index<(usize, usize)> for Grid<T> {
    type Output = T;

    fn index(&self, (x, y): (usize, usize)) -> &T {
        &self.cells[y * self.width + x]
    }
}

impl<T> IndexMut<(usize, usize)> for Grid<T> {
    fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut T {
        &mut self.cells[y * self.width + x]
    }
}

fn main() {
    let mut grid = Grid::new(3, 2, 0u8);
    grid[(1, 0)] = 7;
    println!("cell: {}", grid[(1, 0)]);
    println!("safe lookup: {:?}", grid.get(5, 0));
}

How the snippet works

Count the functions new, get, index and index_mut as the entire surface area of Index Trait For Grid Access.

Applying it

Entry signature: fn new(width: usize, height: usize, fill: T) -> Self

Running the file prints labeled results such as cell:, safe lookup: — each operation’s effect is visible in the output.

Treat main as the orchestrator calling new and get in a fixed order.

Statements that matter

fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut T {
&mut self.cells[y * self.width + x]
}
fn get(&self, x: usize, y: usize) -> Option<&T> {
if x >= self.width {
return None;
}
self.cells.get(y * self.width + x)
}
fn index(&self, (x, y): (usize, usize)) -> &T {
&self.cells[y * self.width + x]
}

Interactive Tools for This Topic

FAQ

What does Index Trait For Grid Access print when run?
Run it as a complete program — the output lines carry labels such as `cell:`, `safe lookup:`.