为什么 std::rc::Rc 可以调用它自己的值的方法?
Why can std::rc::Rc call its own value's methods?
我是 Rust 和类型系统的新手。我正在阅读 rustc/rc.rs。不知道为什么Rc<T>
可以调用T的方法。 a Structure<T>
调用包装值的方法需要满足什么条件?
use std::rc::Rc;
fn main() {
let a = Rc::new("The quick fox".to_string());
println!("{}", a.contains("white")); // Rc<String> can call String#contains.
}
这个属性叫做“Deref
coercion”。
如果你有两种类型 T
和 U
,例如 T: Deref<Target = U>
,那么在任何有 &T
的地方,你都可以 强制 到 &U
。特别是,由于方法调用语法只是采用 &self
(或 &mut self
或 self
- 取决于方法)的函数的糖分,您可以在 U
只有 T
.
如您在文档中所见,Deref
is implemented for Rc
, as it is for almost any other smart pointer (the "active" smart pointers like Mutex
, which involve explicit locking, being notable exception). So, when you have one of these smart pointers, you can treat a reference to it as the reference to the inner value - see also 关于此事实的其他后果。
还可以找到关于此主题的更多信息 in the Rust book。
我是 Rust 和类型系统的新手。我正在阅读 rustc/rc.rs。不知道为什么Rc<T>
可以调用T的方法。 a Structure<T>
调用包装值的方法需要满足什么条件?
use std::rc::Rc;
fn main() {
let a = Rc::new("The quick fox".to_string());
println!("{}", a.contains("white")); // Rc<String> can call String#contains.
}
这个属性叫做“Deref
coercion”。
如果你有两种类型 T
和 U
,例如 T: Deref<Target = U>
,那么在任何有 &T
的地方,你都可以 强制 到 &U
。特别是,由于方法调用语法只是采用 &self
(或 &mut self
或 self
- 取决于方法)的函数的糖分,您可以在 U
只有 T
.
如您在文档中所见,Deref
is implemented for Rc
, as it is for almost any other smart pointer (the "active" smart pointers like Mutex
, which involve explicit locking, being notable exception). So, when you have one of these smart pointers, you can treat a reference to it as the reference to the inner value - see also
还可以找到关于此主题的更多信息 in the Rust book。