std-method

Rust slice::get_mut(): borrow an element with bounds checking

Use get_mut when a requested position might be absent. For a usize index, the result is Some with a mutable element reference or None for an out-of-range index. Ranges can also select subslices. It does not allocate or copy the selected elements. Expected output (not executed): [8, 15] Missing: true Why: The first index exists and is updated; the second is absent. Common mistake: Assuming get_mut returns the element by value or panics on a missing ordinary index.

Formal Syntax & Structure

rust syntaxrust
pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output> where I: SliceIndex<[T]>

Parameters & Attributes

NameTypeDescription
indexI: SliceIndex<[T]>Element index or supported range.

Return Value

Option<&mut I::Output>

Exclusive reference to selected element or subslice, or None if absent.

Working Example

Example Snippetrust
fn main() {    let mut scores = [8, 12];    if let Some(score) = scores.get_mut(1) {        *score += 3;    }    println!("{scores:?}");    println!("Missing: {}", scores.get_mut(4).is_none());}
Rust Reference