Deref

The Deref trait grants the ability to dereference a value as if it were a borrow. Smart pointers implement this trait, which is why they can be used as though they were borrows of the contained data value. String does the same thing, which is what allows us to use a String value anywhere that an &str is expected.

Here we have an implementation of the Deref trait:

pub struct DerefExample {
val: u32,
}

impl Deref for DerefExample {
type Target = u32;

fn deref(&self) -> &u32 {
return &self.val;
}
}

Notice that the implementation function doesn't actually dereference anything. Instead, it converts an &self borrow into a borrow of something else.

That's what the compiler needs in order to correctly and efficiently handle dereferencing smart pointers and such, but the compiler also uses that ability to let us interact with something like a Rc<Box<String>> as if it were just a plain old &str. The Rc has a deref function that returns a borrow of a Box, and the Box has a deref function that returns a  borrow of a String, and the String has a deref function that returns a borrow of a str, so the compiler lets us treat the whole thing as if it was an &str for the purposes of calling its functions or using it as a parameter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.254.192