拥有指针语义的复合类型
借鉴了c++ RAII 机制 栈管理堆内存 自动管理内存的复合类型
trait 决定了类型行为
Deref trait
Drop trait
两者实现其中一个或者两者都实现
Deref trait
实现 Deref trait 允许我们重载 解引用运算符 通过这种方式实现 Deref trait 的智能指针可以被当作常规引用来对待,可以编写操作引用的代码并用于智能指针 通俗来讲实现了 Deref trait 的智能指针可以把智能指针当作智能指针值的引用来对待
use std::ops::Deref;
#[derive(Debug)]
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(x: T) -> MyBox<T> {
MyBox(x)
}
}
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
fn main() {
let x = 5;
let y = MyBox::new(String::from("test"));
assert_eq!(5, x);
println!("{:?}", y.len());
}
如果没有实现Deref trait 会有如下报错
error[E0599]: no method named `len` found for struct `MyBox` in the current scope
--> src/main.rs:26:24
|
8 | struct MyBox<T>(T);
| --------------- method `len` not found for this struct
...
26 | println!("{:?}", y.len());
| ^^^ method not found in `MyBox<String>`
|
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `len`, perhaps you need to implement it:
candidate #1: `ExactSizeIterator`
help: one of the expressions' fields has a method of the same name
|
26 | println!("{:?}", y.0.len());
| ++
参考链接
raii: https://rustwiki.org/zh-CN/rust-by-example/scope/raii.html
通过Dereftrait 将智能指针当作常规引用处理: https://rustwiki.org/zh-CN/book/ch15-02-deref.html