std-method

Result::as_ref / as_mut

Borrow either branch, preserving the original result. Mutable borrowing can update either payload. Expected stdout (not executed): Ok("draft saved") Common mistake: Moving the owned result just to read its contents.

Formal Syntax & Structure

rust syntaxrust
fn as_ref(&self) -> Result<&T, &E>; fn as_mut(&mut self) -> Result<&mut T, &mut E>

Working Example

Example Snippetrust
fn main() {    let mut report: Result<String, String> = Ok("draft".into());    if let Ok(s) = report.as_mut() { s.push_str(" saved"); }    println!("{:?}", report.as_ref());}
Rust Reference