简体   繁体   中英

Understanding deref function in Rust book

I'm going through the Deref section of the Rust book and I have questions about the deref function.

struct MyBox<T>(T);

impl<T> Deref for MyBox<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

Question 1. If the input parameter ( &self ) is already a reference to T why do I need another & when accessing 0 in the body of the function? Wouldn't that create a pointer to the pointer of self &&self which would be redundant?

Question 2: The following deref function below does not compile but if I did the same in the main function it compiles.

fn deref(&self) -> &Self::Target {
    // let my_box: &MyBox<T> = self;
    let my_box: &&MyBox<T> = &self; 
    //this does not compile with either of the above two my_box references
    //it asks for another `&`.
    my_box.0 
}

The code above compiles when used in main function.

fn main() {
    let my_box: &MyBox<i32> = &MyBox(5);
    my_box.0;
}

Q1: &self is a reference to struct MyBox itself, not its inner field. self.0 's type is T, and this is the actual inner field. To make the return type &Self::Target match, you need &self.0 (meaning &(self.0) ) whose type is &T .

Q2: Same as Q1, you need to make the type match. main function's return type is () , and the last statement my_box.0; (notice ; )'s type matches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM