std-method

Option::as_ref and as_mut

Use as_ref to read an owned payload without taking it, or as_mut to modify it in place. The returned reference cannot outlive the borrow of the Option. Expected stdout (not executed): draft saved Common mistake: Calling a consuming method on an owned Option when the original must remain usable.

Formal Syntax & Structure

rust syntaxrust
fn as_ref(&self) -> Option<&T>; fn as_mut(&mut self) -> Option<&mut T>

Working Example

Example Snippetrust
fn main() {    let mut note = Some(String::from("draft"));    if let Some(s) = note.as_mut() { s.push_str(" saved"); }    println!("{}", note.as_ref().unwrap());}
Rust Reference