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
Indexreturns a reference to theOutputtype.- Indexing panics by convention when out of bounds.
- Offer a
getreturningOptionalongside it.
Keywords and builtins used here
GridOptionOutputVecfnforgetimplindexletmainselfstructtypeu8useusizevec
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.
Step 2 of 4 in Operators & access, step 13 of 19 in Traits & generics.