[英]Understanding deref function in Rust book
我正在阅读 Rust 书的Deref部分,我对deref
有疑问。
struct MyBox<T>(T);
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
问题 1. 如果输入参数 ( &self
) 已经是对T
的引用,为什么在访问 function 正文中的0
时还需要另一个&
? 这不会创建一个指向 self &&self
指针的指针吗?
问题 2:下面的deref
无法编译,但如果我在主 function 中执行相同操作,则它可以编译。
fn deref(&self) -> &Self::Target {
// let my_box: &MyBox<T> = self;
let my_box: &&MyBox<T> = &self;
//this does not compile with either of the above two my_box references
//it asks for another `&`.
my_box.0
}
上面的代码在主 function 中使用时编译。
fn main() {
let my_box: &MyBox<i32> = &MyBox(5);
my_box.0;
}
Q1: &self
是对 struct MyBox
本身的引用,而不是它的内部字段。 self.0
的类型是 T,这是实际的内部字段。 要使返回类型&Self::Target
匹配,您需要类型为&T
的&self.0
(意思是&(self.0)
)。
Q2:同Q1,需要进行类型匹配。 main
函数的返回类型为()
,最后一条语句my_box.0;
(注意;
)的类型匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.