Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Option and Result

Option as_ref, as_mut and as_deref

Reference for Rust Option::as_ref, as_mut, as_deref and as_deref_mut: borrow the contents of an Option without consuming it or cloning the value.

Most Option methods take self by value, so calling them on an Option<String> moves the string out and you cannot use the option again. The as_ family converts an &Option<T> or &mut Option<T> into an option of references, so you can inspect or change the contents while the original option stays intact.

as_ref gives Option<&T>, as_mut gives Option<&mut T>, and as_deref goes one step further and applies Deref, turning Option<String> into Option<&str> and Option<Vec<T>> into Option<&[T]>.

Rust
let name: Option<String> = Some("Ada".to_string());
let len = name.as_ref().map(|s| s.len());   // name is still usable
let text: Option<&str> = name.as_deref();

Try it

Rust Borrowing instead of moving

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Editing through as_mut

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
impl<T> Option<T> {
    pub const fn as_ref(&self) -> Option<&T>;
    pub const fn as_mut(&mut self) -> Option<&mut T>;
    pub fn as_slice(&self) -> &[T];
}
impl<T: Deref> Option<T> {
    pub fn as_deref(&self) -> Option<&T::Target>;
}
impl<T: DerefMut> Option<T> {
    pub fn as_deref_mut(&mut self) -> Option<&mut T::Target>;
}
Method Turns Into
as_ref() &Option<T> Option<&T>
as_mut() &mut Option<T> Option<&mut T>
as_deref() &Option<T> where T: Deref Option<&T::Target>
as_deref_mut() &mut Option<T> where T: DerefMut Option<&mut T::Target>
as_slice() &Option<T> a slice of length 0 or 1 (Rust 1.75)

Returns: a new Option that borrows from the original. It never allocates or clones.

Panics: none.

Usage notes

  • Reach for as_ref() before map, unwrap, and_then and friends whenever you want to keep using the option afterwards. opt.unwrap() on an Option<String> consumes it; opt.as_ref().unwrap() does not.
  • as_deref() is what makes Option<String> pattern-match against string literals. match name.as_deref() { Some("admin") => ... } works; matching Option<String> against "admin" does not compile.
  • Common targets: Option<String> becomes Option<&str>, Option<Box<T>> becomes Option<&T>, Option<Vec<T>> becomes Option<&[T]>, Option<PathBuf> becomes Option<&Path>.
  • The result borrows the original, so you cannot mutate or move the source option while the borrowed option is alive. This is the usual source of "cannot borrow as mutable" errors in chains; end the chain first.
  • as_mut is how you edit in place. if let Some(x) = self.field.as_mut() { x.update(); } is the borrow-friendly alternative to if let Some(x) = &mut self.field, and the two are equivalent.
  • Do not confuse with Option<&T>::cloned()/copied(), which go the other direction: they turn Option<&T> into Option<T>. A common idiom is opt.as_ref().cloned() (or just opt.clone()).
  • as_slice lets you treat an option as a zero-or-one element slice, handy for passing to APIs that take &[T] or for chaining with iterator code.