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]>.
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
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.
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
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()beforemap,unwrap,and_thenand friends whenever you want to keep using the option afterwards.opt.unwrap()on anOption<String>consumes it;opt.as_ref().unwrap()does not. as_deref()is what makesOption<String>pattern-match against string literals.match name.as_deref() { Some("admin") => ... }works; matchingOption<String>against"admin"does not compile.- Common targets:
Option<String>becomesOption<&str>,Option<Box<T>>becomesOption<&T>,Option<Vec<T>>becomesOption<&[T]>,Option<PathBuf>becomesOption<&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_mutis how you edit in place.if let Some(x) = self.field.as_mut() { x.update(); }is the borrow-friendly alternative toif 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 turnOption<&T>intoOption<T>. A common idiom isopt.as_ref().cloned()(or justopt.clone()). as_slicelets 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.
Related
Option<T>, take and replace, map and and_then, unwrap family- Lessons: Option, Borrowing