skip to content

In Rust, how do you make `grid[(row, col)]` read and write cells of a `Grid` type, and why must `Index::index` return a reference?

level: middleimportance: should knowfreq 35%

answer

  1. brackets are a trait call
  2. Output, Idx and a borrowed result
  3. writes go through a second trait
  4. sugar for *container.index(i)

basics

~10 s

Implement std::ops::Index<(usize, usize)> with an Output type and fn index(&self, idx) -> &Output, plus IndexMut for writes. grid[i] is sugar for *grid.index(i), so index must lend out data the grid already owns.

solid answer

~40 s

`container[index]` is sugar for `*container.index(index)` when the place is only read, and for `*container.index_mut(index)` when it is assigned or mutably borrowed, so `heat[(1, 2)] = 40.5` and `heat[(1, 2)] += 1.5` both go through `IndexMut`. `IndexMut<Idx>` has `Index<Idx>` as a supertrait and reuses its `Output`; without it, a write fails with E0594. Because `index` returns `&Self::Output`, it can only lend something the grid already stores: returning a reference to a freshly computed value is E0515, so derived values belong in an ordinary method. The leading `*` also means `let t = heat[(1, 2)];` works only when `Output: Copy`; for a non-`Copy` output it is E0507 and callers write `&grid[i]`. By convention an out-of-range index panics, and a `get` method returning `Option` is the non-panicking path.

code

rust · 27 lines
rust
use std::ops::{Index, IndexMut};

struct Grid { cols: usize, cells: Vec<f32> }

impl Index<(usize, usize)> for Grid {
    type Output = f32;
    fn index(&self, (row, col): (usize, usize)) -> &f32 {
        assert!(col < self.cols, "column {col} out of range");
        &self.cells[row * self.cols + col]
    }
}

impl IndexMut<(usize, usize)> for Grid {
    fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut f32 {
        assert!(col < self.cols, "column {col} out of range");
        &mut self.cells[row * self.cols + col]
    }
}

fn main() {
    let mut heat = Grid { cols: 3, cells: vec![0.0; 6] };
    heat[(1, 2)] = 40.5;          // *heat.index_mut((1, 2)) = 40.5
    heat[(1, 2)] += 1.5;          // IndexMut again, then f32's AddAssign
    let t = heat[(1, 2)];         // *heat.index((1, 2)), copied because f32: Copy
    println!("{t}");
    let _ = heat[(0, 3)];         // panics: column 3 out of range
}

go deeper

for a junior

Recall that brackets call Index::index for reads and IndexMut::index_mut for writes, and that out-of-range indexing panics in std collections.

for a middle

Explain the *container.index(i) desugaring, why the result is a reference, and what E0594, E0507 and E0515 mean in an indexing context.

for a senior

Design the index type and Output so misuse is caught: validate coordinates, offer get for fallible lookups, and keep computed values out of index.

for a principal

Decide whether a container should expose brackets at all: indexing promises cheap, panicking, place-like access, and a method-only API may suit types with costly lookups.

## Indexing is a pair of traits Square brackets on a user type are not built in. `std::ops` defines two traits: ```rust 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; } ``` (Simplified from the 1.99.1 library source, which adds stability and diagnostic attributes.) The key terms: - **`Idx`** is a type parameter, so one type can be indexed several ways: a `Grid` can implement `Index<(usize, usize)>` for a cell and `Index<usize>` for a whole row. - **`Output`** is the type the brackets denote. It may be unsized (`?Sized`), so `Index<usize>` for a grid row can return `[f32]`. - **`IndexMut` requires `Index`** with the same `Idx`, and shares its `Output`. There is no `IndexMut` without a matching `Index`. ## How rustc desugars the brackets The `Index` documentation states it directly: `container[index]` is "syntactic sugar for `*container.index(index)`" in an immutable context, and the `index_mut` form is used when a mutable place is needed. For a `Grid` named `heat`: 1. `let t = heat[(1, 2)];` becomes `let t = *heat.index((1, 2));`. The `*` reads through the returned reference, so the value is copied out, which works because `f32` is `Copy`. 2. `heat[(1, 2)] = 40.5;` becomes `*heat.index_mut((1, 2)) = 40.5;`. 3. `heat[(1, 2)] += 1.5;` also uses `index_mut`, then `f32`'s own `AddAssign` on the place. 4. `&heat[(0, 0)]` borrows through `index` without copying, the form you need when `Output` is not `Copy`. Two compile errors come straight out of this desugaring: | Code | Missing piece | rustc 1.99.1 reports | |---|---|---| | `grid[(0, 1)] = 3.0;` with only `Index` | `IndexMut` | E0594, "cannot assign to data in an index of `Grid`", with help "trait `IndexMut` is required to modify indexed content" | | `let first = names[0];` on `Vec<String>` | `Output: Copy` | E0507, "cannot move out of index of `Vec<String>`", suggesting `&names[0]` | ## Why `index` must return a reference The signature returns `&Self::Output` tied to `&self`, so the method can only lend out data that lives inside `self` (or data with a longer lifetime). A tempting design is to compute something on the fly, such as the average of two neighbouring cells, and return `&avg`. That fails with **E0515**, "cannot return reference to local variable `avg`", because `avg` dies when the method returns. The rule of thumb: brackets mean *a place inside the container*. If the value is computed, expose a normal method such as `grid.average(row, col)` that returns it by value. This is also why a `Grid` that stores rows of a flat `Vec<f32>` can offer `grid[1][2]`: `impl Index<usize> for Grid { type Output = [f32]; ... }` returns a slice of the row, and the second bracket uses the slice's own `Index<usize>`. With `IndexMut<usize>` returning `&mut [f32]`, `grid[1][2] = 7.0` works too. ## Panics and the non-panicking path The trait documentation says `index` "May panic if the index is out of bounds", and std's own collections do exactly that. Practical consequences: - Panic with a message naming the bad coordinate, as the `assert!` in this question's example does. A flat `Vec` would otherwise accept `(0, 3)` on a three-column grid as cell `(1, 0)` silently. - `index` and `index_mut` are declared with `#[track_caller]` in the trait, and in rustc 1.99.1 the panic in the example is reported at the indexing line in `main`, not inside the impl, which points the reader at the caller's bug. - Offer `get(&self, row, col) -> Option<&f32>` for callers that expect misses, mirroring `slice::get`. ## Design checklist - Pick `Idx` types that match how callers think: `(usize, usize)` or a small `Cell { row, col }` struct reads better than a hand-computed flat offset. - Implement `IndexMut` only when callers may legitimately overwrite cells; a read-only view implements `Index` alone. - Keep `index` cheap and free of side effects; readers expect brackets to be a lookup. - Do not implement `Deref<Target = Vec<f32>>` just to borrow the `Vec`'s brackets. Indexing looks through `Deref`, so `grid[1]` would then mean the second cell of the flat storage rather than row 1, `grid[1][2]` would fail with E0608 ("cannot index into a value of type `f32`"), and every other `Vec` method would leak into the grid's API. A dedicated `Index` impl keeps the meaning of the brackets yours.

  • How can a Rust `Grid` stored as one flat `Vec<f32>` support `grid[1][2]`?
    Implement `Index<usize>` with `type Output = [f32]` and return the row's slice, `&self.cells[r * cols..(r + 1) * cols]`. `Output` may be unsized, and the second bracket is the slice's own `Index<usize>`. Add `IndexMut<usize>` returning `&mut [f32]` and `grid[1][2] = 7.0` compiles as well.
  • Why does `let first = names[0];` fail for a `Vec<String>` but work for a `Vec<f32>`?
    Indexing desugars to `*names.index(0)`, a read through a reference. Reading a `Copy` value such as `f32` copies it; a `String` cannot be moved out from behind a reference, so rustc reports E0507 and suggests `&names[0]` or `names[0].clone()`.
  • Should a Rust `Index` impl panic or return an `Option` on a bad index?
    The signature returns `&Self::Output`, so it cannot return `Option`; std documents that `index` may panic out of bounds, and its collections do. Panic with a clear message and add a separate `get` method returning `Option<&T>` for callers that expect misses.

  • Implementing Index is enough to allow grid[i] = value assignments.
  • Index::index can return a value it computes, like an average.
  • let x = v[i] moves the element out of a Vec<String>.
  • A type can implement Index for only one index type.
  • IndexMut can declare a different Output from the matching Index.