Sub topic 9
Indexing with Index and IndexMut
This chapter assumes you know traits, associated types, and the difference between & and &mut borrows. It also assumes you have read the earlier chapters on Add and Output.
How `[]` maps to traits
The expression container[idx] calls a method from std::ops. Rust picks the trait from how the result is used:
- In a read context,
container[idx]means*Index::index(&container, idx). - In a write or
&mutcontext, it means*IndexMut::index_mut(&mut container, idx).
Both methods return references, not values. Because of the leading *, g[i] is a place, so you can assign to it, borrow it, or copy out of it.
The trait signatures
pub trait Index<Idx: ?Sized> {
type Output: ?Sized;
fn index(&self, index: Idx) -> &Self::Output;
}
pub trait IndexMut<Idx: ?Sized>: Index<Idx> {
fn index_mut(&mut self, index: Idx) -> &mut Self::Output;
}Three details matter:
IndexMuthasIndexas a supertrait. You cannot implementIndexMutalone, and both share the sameOutput.Idxis a trait parameter, so one type can accept several index types.Outputmay be unsized, for example[i32]orstr.
A grid with two index types
The program below indexes a flat Vec by (row, col) and also by a bare row number. The row version returns a slice, so g[1][2] works.
use std::ops::{Index, IndexMut};
struct Grid {
width: usize,
cells: Vec<i32>,
}
impl Index<(usize, usize)> for Grid {
type Output = i32;
fn index(&self, (row, col): (usize, usize)) -> &i32 {
assert!(col < self.width, "column {col} out of range for width {}", self.width);
&self.cells[row * self.width + col]
}
}
impl IndexMut<(usize, usize)> for Grid {
fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut i32 {
assert!(col < self.width, "column {col} out of range for width {}", self.width);
&mut self.cells[row * self.width + col]
}
}
impl Index<usize> for Grid {
type Output = [i32];
fn index(&self, row: usize) -> &[i32] {
let start = row * self.width;
&self.cells[start..start + self.width]
}
}
fn main() {
let mut g = Grid { width: 3, cells: vec![0; 6] };
g[(1, 2)] = 7;
assert_eq!(g[(1, 2)], 7);
assert_eq!(g[1][2], 7);
assert_eq!(g[1], [0, 0, 7]);
}The assert! on col is deliberate. Without it, (0, 5) on a width-3 grid would silently read the next row's cell. The underlying Vec only panics when the flat index passes the end.
Common errors
- Returning a value.
fn index(&self, ..) -> i32does not match the trait. The method must return a reference intoself. A type that computes its elements on the fly, such as a lazily generated matrix, cannot implementIndex. Give it a method likeget(row, col) -> Tinstead. - Implementing only
IndexMut. This fails with an unsatisfied supertrait error. ImplementIndexfirst. - Expecting
OptionorResult. Indexing has no error channel. Out-of-range access panics by convention, asVecdoes. Offer agetmethod that returnsOption<&T>for callers who want to handle misses. - Moving out of an index.
let s = names[0];fails for a non-Copyelement, becausenames[0]is a place behind a reference. Use&names[0]or.clone().
Exercise
Why can Index::index not return Self::Output directly, and what does that imply for a type whose elements are computed on demand?
Show answer
The signature is fn index(&self, index: Idx) -> &Self::Output, so it must return a reference to data that already lives inside self (or elsewhere outliving the borrow). A computed value would be a temporary that cannot be borrowed past the call. Such a type should not implement Index. It should provide a method that returns an owned value, such as get(i) -> T.