Rust Reference ยท Core Traits
The AsRef and AsMut traits
Reference for the Rust AsRef and AsMut traits: accept String, &str or Path in one function, convert references cheaply, and how they differ from Borrow and From.
AsRef<T> converts &self into &T at almost no cost, and AsMut<T> does the same for &mut. They let one function accept many related types: impl AsRef<str> takes a &str, a String, a Box<str> or a Cow<str>, and impl AsRef<Path> takes a string literal, a String, a PathBuf or an OsStr.
Neither allocates or fails. They only reinterpret what the value already holds. That makes them a good fit for read-only parameters where you do not need to own the data.
fn shout(s: impl AsRef<str>) -> String { s.as_ref().to_uppercase() }
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
pub trait AsRef<T: ?Sized> { fn as_ref(&self) -> &T; } pub trait AsMut<T: ?Sized> { fn as_mut(&mut self) -> &mut T; }
| Name | Description |
|---|---|
T |
The target type. It may be unsized: str, [U], Path, OsStr. |
&self / &mut self |
The value to view. It is not consumed. |
Returns: a reference to the target, with the lifetime of the borrow. By convention the conversion is cheap and never fails or panics.
Usage notes
- Use it for parameters, not for storage.
fn open(p: impl AsRef<Path>)is friendly to callers; keep aPathBufinside your struct once you need to own it. - A type can have several
AsReftargets.StringimplementsAsRef<str>,AsRef<[u8]>,AsRef<OsStr>andAsRef<Path>. If a call is ambiguous, annotate it:AsRef::<str>::as_ref(&s). - Auto-deref:
AsRefis implemented for&Tand&mut TwheneverT: AsRef<U>, which is why&Stringand&&stralso work as arguments. - Not the same as
Borrow.Borrowadditionally promises that equality, ordering and hashing agree with the owned type, which is whatHashMaplookups need.AsRefmakes no such promise. - Not the same as
Deref.Derefis the single, automatic "smart pointer" view of a type;AsRefis explicit and may offer many views. - Not the same as
From.Fromconsumes and produces an owned value;AsRefonly lends a view. - Generic code cost: each concrete argument type creates another monomorphized copy of the function. For big functions, take
&stror&Pathin an inner function and let the generic wrapper call it. - Mutable views with
AsMut<[T]>work forVec<T>, arrays andBox<[T]>. - Implement it for newtypes so they plug into APIs that accept
impl AsRef<str>without exposing the inner field.