Rust programming video tutorial (Advanced) – 011_ 2. Custom box

Time:2021-10-22

Video address

Headline address:https://www.ixigua.com/i677586170644791348…
Station B address:https://www.bilibili.com/video/av81202308/

Source address

GitHub address:https://github.com/anonymousGiga/learn_rus…

Explanation content

Custom smart pointer mybox: implement deref trait
//+++++++Error code+++++++++++++++++

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);
}

//+++++++++Correct code++++++++++++++++

//Implement deref train
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 > {// implement deref trait for mybox
    type Target = T;
    FN deref (& self) - > & T {// Note: the returned value here is a reference, because you generally do not want to dereference to obtain the ownership of the internal value of mybox < T >
        &self.0
    }
}

fn main() {
    let x = 5;
    let y = MyBox::new(x);
    assert_eq!(5, x);
    assert_ eq! (5, *y); // Deref trait can be dereferenced after it is implemented. Using * y is actually equivalent to * (y.deref())
}

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Linghu rushed

Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress:https://github.com/nino-laiqiu/TiTanI recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]