How does AsRef work with str?

I want to write a trait that can take a string slice directly:

use std::path::Path;

trait Trait1 {}

impl Trait1 for str {}
// impl<'a> Trait1 for &'a str {}

fn run<T: Trait1>(_: T) {}
fn run1<T: AsRef<Path>>(_: T) {}

fn main() {
    // E0277: the trait bound `&str: Trait1` is not satisfied
    // run::<&str>("sf");
    run1::<&str>("sf");
}

      

note that

run::<&str>("sf");

      

will not compile unless Trait1

also used for &str

. However, it AsRef

works despite the fact that it only runs for str

. Is there something special about AsRef?

+3


source to share


1 answer


If you check the documentation forAsRef

, you will see that it provides the following implementation:

impl<'a, T, U> AsRef<U> for &'a T where T: AsRef<U> + ?Sized, U: ?Sized

      



That is, str

implementation AsRef<Path>

means it &str

also implements AsRef<Path>

.

+3


source







All Articles