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.
impl Index<usize> for Grid { type Output = i32; fn index(&self, i: usize) -> &i32 { &self.cells[i] } }
Try it
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.
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
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
IndexMutrequiresIndex. It is a subtrait with the sameIdxandOutput.- References only.
indexmust 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 becauseVec<T>: Index<Range<usize>>with an unsizedOutput; use&v[1..3]since the value itself is unsized. HashMapimplementsIndexbut notIndexMut.map["key"]panics when missing, and inserting through[]would be ambiguous. Use theentryAPI for writes.- Compound assignment works (
g[i] += 1) because it takes a mutable place, which callsindex_mut. - Tuples and custom types as keys are fine and often clearer than manual
row * width + colarithmetic 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_uncheckedremoves them inunsafecode.
Related
Vec<T>,HashMap, Index expression,DerefandDerefMut- Lessons: Operator overloading, Slices, Vec