Skip to content
Tutorials Center
My learning

Topics

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.

Rust
fn shout(s: impl AsRef<str>) -> String { s.as_ref().to_uppercase() }

Try it

Rust One function, many argument types

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 AsMut and your own AsRef

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
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 a PathBuf inside your struct once you need to own it.
  • A type can have several AsRef targets. String implements AsRef<str>, AsRef<[u8]>, AsRef<OsStr> and AsRef<Path>. If a call is ambiguous, annotate it: AsRef::<str>::as_ref(&s).
  • Auto-deref: AsRef is implemented for &T and &mut T whenever T: AsRef<U>, which is why &String and &&str also work as arguments.
  • Not the same as Borrow. Borrow additionally promises that equality, ordering and hashing agree with the owned type, which is what HashMap lookups need. AsRef makes no such promise.
  • Not the same as Deref. Deref is the single, automatic "smart pointer" view of a type; AsRef is explicit and may offer many views.
  • Not the same as From. From consumes and produces an owned value; AsRef only lends a view.
  • Generic code cost: each concrete argument type creates another monomorphized copy of the function. For big functions, take &str or &Path in an inner function and let the generic wrapper call it.
  • Mutable views with AsMut<[T]> work for Vec<T>, arrays and Box<[T]>.
  • Implement it for newtypes so they plug into APIs that accept impl AsRef<str> without exposing the inner field.