Skip to content

slice::last

slice methods · Collections

Level: reference · for working programmers

One line: The last element as an Option<&T> — the safe spelling of v[v.len() - 1].

pub const fn last(&self) -> Option<&T>

Stable since 1.0.0; const since 1.56.0.

v[v.len() - 1] fails twice on an empty slice: the subtraction overflows, and the index is out of bounds. v.last() returns None instead. It is also the answer to "negative indices" — Python's xs[-1] is xs.last(), and the Option is the IndexError moved into the type.

It borrows, like first. Vec::pop is the owning version: it removes and returns the last element. split_last gives the last element and everything before it.

Example

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

fn main() {
    let nums = [10, 20, 30];
    let empty: [i32; 0] = [];
    println!("{:?} {:?}", nums.last(), empty.last());

    // v[v.len() - 1] on an empty slice overflows before it can even index.
    // last() is the safe spelling, and the Python xs[-1].
    let newest = nums.last().copied().unwrap_or(0);
    println!("newest {newest}");

    // Borrowed, not removed.
    println!("{:?} still has {} elements", nums.last(), nums.len());

    // Everything before the last one.
    if let Some((last, rest)) = nums.split_last() {
        println!("last {last}, rest {rest:?}");
    }
}

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

Some(30) None
newest 30
Some(30) still has 3 elements
last 30, rest [10, 20]

See also

slice::last in the standard library ↗