IMP的原始特征和参考
也许这是一个简单的问题,但是我不明白为什么要对原始的,拥有类型的类型提示特征,我免费获得了参考类型的同一含义...
trait Cool: Sized + std::fmt::Debug {
fn cool(self) {
println!("cool -> {:?}", self);
}
}
impl Cool for i32 {}
// it still works if this line is uncommented...
// impl Cool for &i32 {}
fn main(){
let val = 123;
val.cool();
(&val).cool();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不仅是因为原始人,它将适用于实现
复制
。否则就不会工作:使用明确的错误代码失败:
Playground
发生的事情是,使用副本类型,Rust在需要时为您透明地创建了副本。
请注意,即使我们评论上一行
// nc.cool();
,它也会失败,这显然会移动值...It is not just because of primitives, it will work for all types that implement
Copy
. Will not work otherwise:Fails with a clear error code:
Playground
What it's happening is that with the Copy types rust creates a copy transparently for you when needed.
Note that it fails even if we comment out the previous line
// nc.cool();
, which obviously moves the value...这是自动提出的;每当您使用
。
运算符时,它都适用。它的目的是消除。
和- >
之间的区别,该>在C和相关语言中存在。它是在
That's auto-dereferencing; it applies whenever you use the
.
operator. It's meant to erase the distinction between.
and->
which exists in C and related languages.It was introduced in RFC 241.