trait

AsRef — borrowed conversion

AsRef exposes a cheap shared reference to another type. A generic function can accept String and &str through AsRef<str>. This is not a request to clone or allocate a new owned value. Expected stdout (not executed): 5 2 Common mistake: Confusing AsRef with a conversion that creates an owned String.

Formal Syntax & Structure

rust syntaxrust
fn as_ref(&self) -> &T

Working Example

Example Snippetrust
fn length<T: AsRef<str>>(text: T) -> usize { text.as_ref().len() }fn main() {    let text = String::from("hello");    println!("{} {}", length(&text), length("hi"));}
Rust Reference