简体   繁体   中英

Why is String -> &str different in the impl for Deref and AsRef?

Why does ops::Deref take a String to a &str differently then AsRef ?

This is the impl in ops::Deref

impl ops::Deref for String {
    type Target = str;

    #[inline]
    fn deref(&self) -> &str {
        unsafe { str::from_utf8_unchecked(&self.vec) }
    }
}

That's different from AsRef ,

impl AsRef<str> for String {
    #[inline]
    fn as_ref(&self) -> &str {
        self
    }
}

What is the difference here between .as_ref() and .deref()

You can put a &String where &str is asked due to a type coercion rule:

&T or &mut T to &U if T implements Deref<Target = U>

T is String and U is str in this case.

 impl ops::Deref for String { type Target = str; #[inline] fn deref(&self) -> &str { unsafe { str::from_utf8_unchecked(&self.vec) } } }

And as you can see, this rule relies on the trait Deref . And This is what @user4815162342 says as_ref() relies on deref() to do the actual work means.

For more info about type coercion, see Coercions Types .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM