Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Operators and Expressions

The [] index operator

Reference for Rust indexing with []: arrays, slices, Vec, HashMap and String, the Index and IndexMut traits, bounds-check panics and the get alternatives.

The expression a[i] reads or writes one element (or a sub-slice) of a collection. For arrays and slices it is built into the language; for everything else it calls the Index trait (*a.index(i)) or, in a mutable context, IndexMut (*a.index_mut(i)). That is why Vec, HashMap, String, VecDeque and your own types can all use the same syntax.

Indexing is checked: an out-of-range index or missing key panics instead of reading garbage. When you cannot guarantee the index is valid, use the get family of methods, which return an Option.

Rust
let third = values[2];
values[0] = 99;
let part = &text[1..4];

Try it

Rust Indexing built-in types

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 Implementing Index and IndexMut

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 index type: usize for arrays, slices, Vec and VecDeque; any Range* for sub-slices; &Q for maps; anything you choose for your own types.
Output The element type (or the slice type for ranges).

Returns: a place of type Output. a[i] is sugar for *a.index(i), so reading a non-Copy element by value (let s = names[0]; with Strings) is a move-out error; borrow it (&names[0]) or clone it.

Panics: index out of bounds: the len is 3 but the index is 5 for slices, arrays and Vec; slice index starts at 4 but ends at 2 for reversed ranges; a char-boundary message for str; and the map Index impls panic on a missing key.

Usage notes

  • The index must be usize. v[i] with i: i32 is a compile error; write v[i as usize] or keep counters as usize. This is deliberate: it forces you to think about negative values.
  • Arrays with a constant index that is provably out of range ([1, 2, 3][5]) are rejected at compile time by the unconditional_panic lint.
  • HashMap/BTreeMap implement only Index. To insert or modify, use insert, entry or get_mut.
  • String and str cannot be indexed by an integer, because bytes are not characters. Slice by byte range (&s[0..3], which panics off a char boundary), or use chars(), char_indices() and get(range).
  • Performance: each v[i] pays a bounds check. Iterators (for x in &v, v.iter().sum()) avoid it and are usually just as fast or faster. In hot loops, slice once or use get_unchecked (unsafe) only after measuring.
  • Borrowing: v[i] borrows all of v for the duration of the access. v[0] = v[1] works for Copy elements, but let (a, b) = (&mut v[0], &mut v[1]) does not; use split_at_mut or swap.
  • Custom types: index with a tuple, an enum or a newtype. Return a reference into your own storage; you cannot return a computed value from index.
  • Compound use: m[(i, j)] += 1.0 needs IndexMut, as the example shows.