[英]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::Deref
将String
转换为&str
与AsRef
不同?
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
isString
andU
isstr
in this case.在这种情况下,
T
是String
,U
是str
。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.