slice::first_mut¶
Level: reference · for working programmers
One line: A mutable reference to the first element, or None on an empty slice.
Stable since 1.0.0; const since 1.83.0.
v[0] = x panics on an empty vector; if let Some(first) = v.first_mut() { *first = x; } does nothing instead. Same asking-not-asserting split as first, with a &mut T inside the Some.
While that &mut is alive the whole slice is mutably borrowed — no reading, no pushing, until it is dropped. if let scopes it neatly; binding it with let and then using the vector is the E0502 everybody meets.
Example¶
slice_first_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(first) = nums.first_mut() {
*first = 10;
}
println!("{nums:?}");
// On an empty vector nums[0] = 10 would panic; this is a no-op.
let mut empty: Vec<i32> = vec![];
if let Some(first) = empty.first_mut() {
*first = 10;
}
println!("{:?}", empty.first_mut());
println!("{empty:?}");
// The &mut is a whole-slice borrow while it lives.
let mut words = vec![String::from("a"), String::from("b")];
let first = words.first_mut().unwrap();
first.push_str("da");
// println!("{words:?}"); // error[E0502] here: `first` is still alive
println!("{first}");
println!("{words:?}"); // fine: `first` was last used above
}
Verified output of slice_first_mut.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
slice::first— read-onlyslice::last_mut— the other endslice::get_mut— any index, writable