typestar

Implementing Index in Rust

Index gives your type the square-bracket syntax, borrowing what it returns.

use std::ops::Index;

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

impl Index<(usize, usize)> for Grid {
    type Output = u8;

    fn index(&self, (row, col): (usize, usize)) -> &u8 {
        &self.cells[row * self.width + col]
    }
}

impl Grid {
    fn get(&self, row: usize, col: usize) -> Option<&u8> {
        self.cells.get(row * self.width + col)
    }
}

fn main() {
    let grid = Grid { width: 3, cells: vec![1, 2, 3, 4, 5, 6] };
    println!("{}", grid[(1, 2)]);
    println!("{:?} {:?}", grid.get(0, 1), grid.get(9, 9));
}

How it works

  1. Index returns a reference to the Output type.
  2. Indexing panics by convention when out of bounds.
  3. Offer a get returning Option alongside it.

Keywords and builtins used here

The run, in numbers

Lines
26
Characters to type
490
Tokens
191
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 109 seconds.

Type this snippet

Step 2 of 4 in Operators & access, step 13 of 19 in Traits & generics.

← Previous Next →