std-method

Option::as_deref / as_deref_mut

Borrow the dereference target of an optional smart pointer or String. This is useful for passing Option<&str> without consuming Option<String>. Expected stdout (not executed): Some("Mina") Common mistake: Expecting the returned reference to outlive the owner.

Formal Syntax & Structure

rust syntaxrust
fn as_deref(&self) -> Option<&T::Target> where T: std::ops::Deref; fn as_deref_mut(&mut self) -> Option<&mut T::Target> where T: std::ops::DerefMut

Working Example

Example Snippetrust
fn main() {    let name = Some(String::from("Mina"));    let view: Option<&str> = name.as_deref();    println!("{view:?}");}
Rust Reference