2021年3月19日星期五

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;  }  
https://stackoverflow.com/questions/66717989/understanding-deref-function-in-rust-book March 20, 2021 at 11:38AM

没有评论:

发表评论