Sub topic 9
Indexing with Index and IndexMut
This chapter assumes you know how to implement a trait, how associated types work, and how shared and mutable borrows differ. You should also have seen Add and its Output type in earlier chapters. The new ideas here are that indexing returns a reference, that one expression can call two different methods, and that a bad index should panic.
What `a[i]` expands to
The expression container[idx] is sugar for a method call on one of two traits in std::ops:
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 separate these traits from Add:
- Both methods return a reference.
container[idx]means*container.index(idx)or*container.index_mut(idx). The dereference makes the result a place expression, so you can assign to it, borrow it, or read it. IndexMuthasIndexas a supertrait. The two traits share oneOutputtype, so reading and writing always agree on the element type.OutputandIdxmay be unsized (?Sized). This is whyVec<T>can produce a[T]slice from a range index.
The compiler picks the method from the context of the expression.
A first implementation: a 2D grid
A grid stores its cells in one flat Vec and is addressed by a (row, col) pair. The index type is the tuple (usize, usize).
use std::ops::{Index, IndexMut};
struct Grid {
width: usize,
height: usize,
cells: Vec<i32>,
}
impl Grid {
fn new(width: usize, height: usize) -> Self {
Grid { width, height, cells: vec![0; width * height] }
}
fn offset(&self, row: usize, col: usize) -> usize {
assert!(
row < self.height && col < self.width,
"index ({row}, {col}) out of bounds for {}x{} grid",
self.height,
self.width
);
row * self.width + col
}
}
impl Index<(usize, usize)> for Grid {
type Output = i32;
fn index(&self, (row, col): (usize, usize)) -> &i32 {
&self.cells[self.offset(row, col)]
}
}
impl IndexMut<(usize, usize)> for Grid {
fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut i32 {
let i = self.offset(row, col);
&mut self.cells[i]
}
}
fn main() {
let mut g = Grid::new(3, 2);
g[(1, 2)] = 7;
g[(1, 2)] += 1;
assert_eq!(g[(1, 2)], 8);
let cell = &mut g[(0, 0)];
*cell = 5;
assert_eq!(g[(0, 0)], 5);
}Each line in main uses a different path:
g[(1, 2)] = 7andg[(1, 2)] += 1callindex_mut. The compound assignment works because thei32itself implementsAddAssign.assert_eq!(g[(1, 2)], 8)reads the cell throughindex.&mut g[(0, 0)]callsindex_mutand gives you a&mut i32that holds a mutable borrow of the whole grid until its last use.
Bounds checking is your job
The offset helper asserts both coordinates. Without it, g[(0, 5)] on a 3-wide grid would silently read from row 1, because 0 * 3 + 5 is a valid position in the flat Vec. The Vec only checks the flat length, so it cannot catch a column that is too large. The standard library's convention is that indexing panics on invalid input, so do the same and put the offending values in the message.
Several index types on one type
A type can implement Index many times, once per index type. The compiler selects the impl from the type of the index expression. Here the grid gains a second impl that takes a single usize and returns a whole row as a slice:
use std::ops::{Index, IndexMut};
struct Grid {
width: usize,
height: usize,
cells: Vec<i32>,
}
impl Index<usize> for Grid {
type Output = [i32];
fn index(&self, row: usize) -> &[i32] {
assert!(row < self.height, "row {row} out of bounds");
let start = row * self.width;
&self.cells[start..start + self.width]
}
}
impl IndexMut<usize> for Grid {
fn index_mut(&mut self, row: usize) -> &mut [i32] {
assert!(row < self.height, "row {row} out of bounds");
let start = row * self.width;
&mut self.cells[start..start + self.width]
}
}
fn main() {
let mut g = Grid { width: 3, height: 2, cells: vec![0; 6] };
g[1][2] = 9;
assert_eq!(g[1], [0, 0, 9]);
assert_eq!(g[1][2], 9);
}Output = [i32] is an unsized type, which is allowed because of Output: ?Sized. The expression g[1][2] first resolves g[1] to a place of type [i32], then applies the built-in slice indexing to it. Because g[1][2] = 9 is an assignment, the compiler uses index_mut for the first step as well.
If you combine this impl with the tuple impl from the previous section, both live on Grid without conflict. The types usize and (usize, usize) are different Idx arguments, so these are different trait implementations.
Indexing by key
The index can be any type, including a borrowed string. This wrapper makes a HashMap readable with [] syntax and panics with a useful message on a missing key:
use std::collections::HashMap;
use std::ops::Index;
struct Settings {
values: HashMap<String, f64>,
}
impl<'a> Index<&'a str> for Settings {
type Output = f64;
fn index(&self, key: &'a str) -> &f64 {
self.values
.get(key)
.unwrap_or_else(|| panic!("no setting named {key:?}"))
}
}
fn main() {
let mut values = HashMap::new();
values.insert("gain".to_string(), 2.5);
let s = Settings { values };
assert_eq!(s["gain"], 2.5);
}This type implements only Index. It has no IndexMut, so s["gain"] = 1.0 does not compile. The standard HashMap makes the same choice. Writing needs an insertion path that can create entries, and IndexMut has no way to express "create this key". A read-only Index plus an explicit insert method is a normal design.
Limits and common errors
| Symptom | Cause | Fix |
|---|---|---|
| `cannot move out of index of Vec<String>` | `v[0]` is a place of type `String`, and `let s = v[0];` tries to move it out from behind a reference. | Borrow with `&v[0]`, clone it, or use `std::mem::take`. |
| Cannot return a computed value from `index` | `index` must return `&Self::Output`, so the value has to live inside `self`. | Store the value, or provide a method such as `get(i) -> T`. |
| `g[(1, 2)] = 7` fails with "cannot borrow as mutable" | The type implements `Index` but not `IndexMut`, or the binding is not `mut`. | Implement `IndexMut`, and declare the variable with `let mut`. |
| Cannot return `Option` or `Result` from indexing | The signature is fixed. Failure can only be a panic. | Add a `get(&self, idx) -> Option<&T>` method next to the operator. |
| Two simultaneous `&mut g[a]` and `&mut g[b]` are rejected | Each call to `index_mut` borrows all of `g` mutably. | Use `split_at_mut`, or restructure so you hold one reference at a time. |
The last row is the most common surprise. The borrow checker sees index_mut(&mut self, ...), so it cannot know that two indices refer to disjoint cells. Operator syntax cannot express disjoint borrows.
Design guidance
Implement Index when the value is a stored element that can be named by a position or a key. Implement IndexMut only if callers should be able to overwrite elements in place. Keep the semantics predictable: the same index should always refer to the same element, and the indexing should cost O(1) or close to it. If the operation does real computation, or can fail in ways callers need to handle, use a named method instead.
Exercise
A Matrix type stores its values in a Vec<f64> and implements Index<(usize, usize)> with Output = f64. A colleague wants m[(0, 0)] to return the average of the cell and its four neighbours, computed on the fly, and asks you to change index to return f64. Why does this not compile, and what should they do instead?
Show answer
Index::index must return &Self::Output, a reference into data that outlives the call. A computed average is a temporary local value, so no reference to it can be returned, and the signature cannot be changed to return f64. They should leave Index for the stored cells and add a named method such as fn neighbourhood_mean(&self, row: usize, col: usize) -> f64. A method can return an owned value and signals that the cost is more than a lookup.
Exercise
Given let mut g = Grid::new(3, 2); using the tuple-indexed Grid from this chapter, which trait method does each of these call: let x = g[(0, 1)];, g[(0, 1)] += 4;, and let r = &g[(0, 1)];?
Show answer
let x = g[(0, 1)]; calls index, because it only reads, and i32 is Copy. g[(0, 1)] += 4; calls index_mut, because compound assignment needs a mutable place. let r = &g[(0, 1)]; calls index, because a shared borrow only needs &Output.