Skip to content

slice::last_mut

slice methods · Collections

Level: reference · for working programmers

One line: A mutable reference to the last element, or None on an empty slice.

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

Stable since 1.0.0; const since 1.83.0.

The writable last. Its everyday job is append to the most recent thing: a line to the last paragraph, a value to the last group, without popping and pushing it back.

If there is no last element and you want one, that is Vec::push, not this — last_mut never creates.

Example

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

fn main() {
    let mut nums = vec![1, 2, 3];
    if let Some(last) = nums.last_mut() {
        *last *= 100;
    }
    println!("{nums:?}");

    // Append to the most recent group without pop-and-push.
    let mut groups: Vec<Vec<&str>> = vec![vec!["a"], vec!["b"]];
    groups.last_mut().unwrap().push("c");
    println!("{groups:?}");

    // last_mut never creates: on an empty Vec it is None, and push is the answer.
    let mut empty: Vec<Vec<&str>> = vec![];
    match empty.last_mut() {
        Some(group) => group.push("x"),
        None => empty.push(vec!["x"]),
    }
    println!("{empty:?}");
}

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

[1, 2, 300]
[["a"], ["b", "c"]]
[["x"]]

See also

slice::last_mut in the standard library ↗