AsRef and &T

RecipeCrates
AsRef and &Tstd

The AsRef trait in Rust is used for cheap reference-to-reference conversions. It provides a way to convert an object into a reference to another type. This trait is often used to allow functions to accept arguments in multiple forms.


fn print_length<T: AsRef<str>>(s: T) {
    let s_ref: &str = s.as_ref();
    println!("The length of '{}' is {}", s_ref, s_ref.len());
}

fn main() {
    let string = String::from("Hello, world!");
    let str_slice = "Hello, Rust!";

    // Using print_length with a String
    print_length(string);

    // Using print_length with a &str
    print_length(str_slice);
}

NOTES:

  • AsRef is similar to AsMut which is used for converting between mutable references.
  • If you need to do a costly conversion, it is better to implement From with type &T or write a custom function.

When and why to use AsRefinstead of &T