Rust AsRef & AsMut


Example

std::convert::AsRef and std::convert::AsMut are used for cheaply converting types to references. For types A and B,

impl AsRef<B> for A

indicates that a &A can be converted to a &B and,

impl AsMut<B> for A

indicates that a &mut A can be converted to a &mut B.

This is useful for performing type conversions without copying or moving values. An example in the standard library is std::fs::File.open():

fn open<P: AsRef<Path>>(path: P) -> Result<File>

This allows File.open() to accept not only Path, but also OsStr, OsString, str, String, and PathBuf with implicit conversion because these types all implement AsRef<Path>.