Rust 程式設計視訊教程(進階)——011_2 自定義 Box

linghuyichong發表於2020-01-28

頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

github地址:https://github.com/anonymousGiga/learn_rus...

自定義智慧指標MyBox:實現Deref trait
//+++++++錯誤程式碼+++++++++++++++++

struct MyBox<T>(T);
impl<T> MyBox<T> {
    fn new(x: T) -> MyBox<T> {
        MyBox(x)
    }
}

fn main() {
    let x = 5;
    let y = MyBox::new(x);
    assert_eq!(5, x);
    assert_eq!(5, *y);
}

//+++++++++正確程式碼++++++++++++++++

//實現Deref Trait
use std::ops::Deref;
struct MyBox<T>(T);
impl<T> MyBox<T> {
    fn new(x: T) -> MyBox<T> {
        MyBox(x)
    }
}

impl<T> Deref for MyBox<T> { //為MyBox實現Deref trait
    type Target = T;
    fn deref(&self) -> &T { //注意:此處返回值是引用,因為一般並不希望解引用獲取MyBox<T>內部值的所有權
        &self.0
    }
}

fn main() {
    let x = 5;
    let y = MyBox::new(x);
    assert_eq!(5, x);
    assert_eq!(5, *y); //實現Deref trait後即可解引用,使用*y實際等價於 *(y.deref())
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

令狐一衝

相關文章