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.
let third = values[2]; values[0] = 99; let part = &text[1..4];
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 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]withi: i32is a compile error; writev[i as usize]or keep counters asusize. 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 theunconditional_paniclint. HashMap/BTreeMapimplement onlyIndex. To insert or modify, useinsert,entryorget_mut.Stringandstrcannot be indexed by an integer, because bytes are not characters. Slice by byte range (&s[0..3], which panics off a char boundary), or usechars(),char_indices()andget(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 useget_unchecked(unsafe) only after measuring. - Borrowing:
v[i]borrows all ofvfor the duration of the access.v[0] = v[1]works forCopyelements, butlet (a, b) = (&mut v[0], &mut v[1])does not; usesplit_at_mutorswap. - 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.0needsIndexMut, as the example shows.
Related
- .. and ..=
- . member access
- * dereference
- Tutorial: Arrays, Slices, Vec, HashMap