简体   繁体   English

为什么 String -> &str 在 Deref 和 AsRef 的实现中不同?

[英]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 ?为什么ops::DerefString转换为&strAsRef不同?

This is the impl in ops::Deref这是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 ,这与AsRef不同,

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

What is the difference here between .as_ref() and .deref() .as_ref().deref()之间有什么区别

You can put a &String where &str is asked due to a type coercion rule:由于类型强制规则,您可以在询问&str的地方放置一个&String

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

T is String and U is str in this case.在这种情况下, TStringUstr

 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 .如您所见,此规则依赖于特征Deref And This is what @user4815162342 says as_ref() relies on deref() to do the actual work means.这就是 @user4815162342 所说as_ref() relies on deref() to do the actual work

For more info about type coercion, see Coercions Types .有关类型强制的更多信息,请参阅强制类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么选择<String> .as_ref() 不解除对 Option&lt;&amp;str&gt; 的引用? - Why does Option<String>.as_ref() not deref to Option<&str>? 为什么stringstream :: str()截断字符串? - Why stringstream::str() truncates string? 为什么String :: find不是&str的方法? - Why is String::find not a method on &str? string和string.c_str()的值不同 - different values of string and string.c_str() 为什么 Rust 中的字符串文字是 &amp;str 而不是 String? - Why are string literals &str instead of String in Rust? 为什么这些字符串的 str == str.intern() 结果不同? - Why are the results of of str == str.intern() for these strings different? 为什么使用append或者不同的StringBuilder的str == str.intern()的结果? - Why are the results of of str == str.intern() for StringBuilder using append or not different? 为什么str.count(&#39;&#39;)和len(str)给出不同的输出? - Why are str.count('') and len(str) giving different output? 为什么String.IsNullOrEmpty(str)而不是str.IsNullOrEmpty()? - Why String.IsNullOrEmpty(str) and not str.IsNullOrEmpty()? 为什么`str`封装在`String`中,而不是封装在`Box中 <str> `? - Why is `str` encapsulated inside `String` instead of inside a `Box<str>`?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM