Skip to content

slice::get

slice methods · Collections

Level: reference · for working programmers

One line: An element, or a sub-slice, as an OptionNone where v[i] would panic.

pub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>
where
    I: SliceIndex<[T]>,

Stable since 1.0.0. Its const form is still unstable.

v[i] asserts the index is in range and panics otherwise; v.get(i) asks, and returns None. The I: SliceIndex<[T]> bound is what lets one method take two kinds of index:

index returns out of range
usize Option<&T> None
a range Option<&[T]> Nonenot clamped

v.get(1..99) on a four-element slice is None, not Some(&v[1..4]); a range that is partly out of bounds fails whole. A reversed range, 3..1, is None too. An empty range at the very end, v.get(4..) on four elements, is Some([]), the same as &v[4..].

The Some holds a reference. To keep the value after the slice is gone, or to avoid the &, copied (for Copy types) or cloned on the Option.

Example

slice_get.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let v = vec![10, 20, 30, 40];
    println!("{:?} {:?}", v.get(1), v.get(9));

    // A range index returns a sub-slice, or None if ANY of it is out of range.
    println!("{:?}", v.get(1..3));
    println!("{:?}  <- not clamped, not a panic", v.get(1..99));
    println!("{:?}  <- reversed range", v.get(3..1));
    println!("{:?}  <- empty range at the end is fine", v.get(4..));

    // v[idx] would panic on 9; get is the question form.
    let idx = 9;
    println!("{}", v.get(idx).copied().unwrap_or(0));

    // The Some holds a reference; copied() turns Option<&i32> into Option<i32>.
    let third = v.get(2).copied();
    println!("{third:?}");
}

Verified output of slice_get.rs — regenerated by tools/run_examples.py, never hand-typed.

Some(20) None
Some([20, 30])
None  <- not clamped, not a panic
None  <- reversed range
Some([])  <- empty range at the end is fine
0
Some(30)

See also

slice::get in the standard library ↗