slice::get_mut¶
Level: reference · for working programmers
One line: A mutable reference to an element or a sub-slice, or None when the index is out of range.
pub fn get_mut<I>(&mut self, index: I) -> Option<&mut <I as SliceIndex<[T]>>::Output>
where
I: SliceIndex<[T]>,
Stable since 1.0.0. Its const form is still unstable.
The writable get: a usize gives Option<&mut T>, a range gives Option<&mut [T]>, and a range that is anywhere out of bounds gives None rather than a shorter slice.
Two elements at once is the trap. let a = v.get_mut(0); let b = v.get_mut(3); is error[E0499]: cannot borrow `v` as mutable more than once — each call borrows the whole slice. get_mut cannot know the two indices differ; get_disjoint_mut ↗ checks that at run time and hands back both (stable since 1.86), split_at_mut ↗ divides the slice into two halves you may borrow independently, and swap covers the commonest reason for wanting two.
Example¶
slice_get_mut.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let mut v = vec![1, 2, 3, 4];
if let Some(x) = v.get_mut(1) {
*x = 20;
}
println!("{v:?}");
// Out of range: None, and the if-let body never runs.
if let Some(x) = v.get_mut(9) {
*x = 90;
}
println!("{v:?}");
// A range gives a &mut [T].
if let Some(tail) = v.get_mut(2..) {
tail.fill(0);
}
println!("{v:?}");
// Two at once is refused: a second get_mut while the first is alive is
// error[E0499]. get_disjoint_mut checks the indices differ, at run time.
let [a, b] = v.get_disjoint_mut([0, 3]).unwrap();
std::mem::swap(a, b);
println!("{v:?}");
println!("{:?}", v.get_disjoint_mut([0, 0]).is_err());
}
Verified output of slice_get_mut.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
slice::get— read-onlyslice::first_mut— index 0, writableslice::swap— the usual reason for wanting two&mut