Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Core Traits

The Index and IndexMut traits

Reference for Rust Index and IndexMut: overloading the [] operator, the Output type, custom index types, ranges, panics, and why HashMap has no IndexMut.

Index and IndexMut define what container[key] means for your type. Index::index returns a shared reference, and IndexMut::index_mut returns a mutable reference. The compiler picks one by context: reads use Index, writes and &mut borrows use IndexMut.

container[key] is sugar for *container.index(key) (or *container.index_mut(key) in a mutable context). The key type is a generic parameter, so one container can accept several index types such as usize, ranges, or your own enums.

Rust
impl Index<usize> for Grid {
    type Output = i32;
    fn index(&self, i: usize) -> &i32 { &self.cells[i] }
}

Try it

Rust A grid indexed by row and column

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Several index types and a panic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

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;
}
Name Description
Idx The key type inside the brackets. A type can implement Index for several Idx types.
Output What container[key] evaluates to. May be unsized, like str or [T].
index The key, passed by value.

Returns: a reference to the element, tied to the borrow of self.

Errors / panics / edge cases: the traits cannot return Result or Option, so an invalid key must panic. Vec, slices and arrays panic with "index out of bounds". Provide a get method for a non-panicking lookup.

Usage notes

  • IndexMut requires Index. It is a subtrait with the same Idx and Output.
  • References only. index must return a reference into the container. You cannot compute and return a fresh value; build a method instead.
  • Slices and ranges are Output = [T]. v[1..3] works because Vec<T>: Index<Range<usize>> with an unsized Output; use &v[1..3] since the value itself is unsized.
  • HashMap implements Index but not IndexMut. map["key"] panics when missing, and inserting through [] would be ambiguous. Use the entry API for writes.
  • Compound assignment works (g[i] += 1) because it takes a mutable place, which calls index_mut.
  • Tuples and custom types as keys are fine and often clearer than manual row * width + col arithmetic at call sites.
  • Auto-deref helps. Indexing a Box<Vec<T>> or &Vec<T> works because the indexing expression auto-dereferences the container.
  • Bounds checks cost a comparison per access. Iterators avoid them; get_unchecked removes them in unsafe code.