AsRef and &T
Recipe | Crates |
---|---|
AsRef and &T |
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.
/// This function takes a generic type `T` that implements the `AsRef<str>` /// trait. It converts the input `s` to a string slice (`&str`) using /// `as_ref()`. /// /// # Arguments /// /// * `s` - A value of type `T` that can be converted to a string slice. fn print_length<T: AsRef<str>>(s: T) { let s_ref: &str = s.as_ref(); // Print the string slice and its length. 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 toAsMut
⮳, 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 AsRef
Related Topics
- Smart Pointers.