What is the Borrow trait vs AsRef

Borrow treats wrappers as references to inner data, while AsRef converts values to references of other types for generic flexibility.

Use Borrow when you need to treat a smart pointer or wrapper as a reference to its inner data, and use AsRef when you need to convert a value into a reference of a different type in generic code. Borrow is typically implemented for smart pointers to allow them to be used where references are expected, while AsRef is a more general conversion trait used to accept multiple input types that can be converted to a specific reference type.

use std::borrow::Borrow;
use std::convert::AsRef;

fn takes_ref(s: &str) {
    println!("{}", s);
}

fn takes_as_ref<T: AsRef<str>>(s: T) {
    println!("{}", s.as_ref());
}

fn main() {
    let owned = String::from("hello");
    let borrowed: &str = &owned; // Implicit Borrow
    takes_ref(borrowed);
    takes_as_ref(owned); // Explicit AsRef
}