trait

AsMut — mutable borrowed conversion

AsMut provides a cheap mutable reference conversion. A Vec can expose its slice for in-place changes. The mutable reference remains subject to ordinary exclusive access rules. Expected stdout (not executed): [9, 2] Common mistake: Expecting as_mut to work on an immutable binding or to resize a borrowed slice.

Formal Syntax & Structure

rust syntaxrust
fn as_mut(&mut self) -> &mut T

Working Example

Example Snippetrust
fn set_first<T: AsMut<[u8]>>(mut data: T) { if let Some(first) = data.as_mut().first_mut() { *first = 9; } }fn main() {    let mut data = vec![1u8, 2];    set_first(&mut data);    println!("{data:?}");}
Rust Reference