拥有指针语义的复合类型

    借鉴了c++ RAII 机制 栈管理堆内存 自动管理内存的复合类型

    trait 决定了类型行为

    Deref trait

    Drop trait

    两者实现其中一个或者两者都实现

    Deref trait

    实现 Deref trait 允许我们重载 解引用运算符 通过这种方式实现 Deref trait 的智能指针可以被当作常规引用来对待,可以编写操作引用的代码并用于智能指针 通俗来讲实现了 Deref trait 的智能指针可以把智能指针当作智能指针值的引用来对待
    1. use std::ops::Deref;
    2. #[derive(Debug)]
    3. struct MyBox<T>(T);
    4. impl<T> MyBox<T> {
    5. fn new(x: T) -> MyBox<T> {
    6. MyBox(x)
    7. }
    8. }
    9. impl<T> Deref for MyBox<T> {
    10. type Target = T;
    11. fn deref(&self) -> &T {
    12. &self.0
    13. }
    14. }
    15. fn main() {
    16. let x = 5;
    17. let y = MyBox::new(String::from("test"));
    18. assert_eq!(5, x);
    19. println!("{:?}", y.len());
    20. }

    如果没有实现Deref trait 会有如下报错

    1. error[E0599]: no method named `len` found for struct `MyBox` in the current scope
    2. --> src/main.rs:26:24
    3. |
    4. 8 | struct MyBox<T>(T);
    5. | --------------- method `len` not found for this struct
    6. ...
    7. 26 | println!("{:?}", y.len());
    8. | ^^^ method not found in `MyBox<String>`
    9. |
    10. = help: items from traits can only be used if the trait is implemented and in scope
    11. = note: the following trait defines an item `len`, perhaps you need to implement it:
    12. candidate #1: `ExactSizeIterator`
    13. help: one of the expressions' fields has a method of the same name
    14. |
    15. 26 | println!("{:?}", y.0.len());
    16. | ++

    参考链接

    raii: https://rustwiki.org/zh-CN/rust-by-example/scope/raii.html

    通过Dereftrait 将智能指针当作常规引用处理: https://rustwiki.org/zh-CN/book/ch15-02-deref.html