October 2018
Beginner
180 pages
4h 48m
English
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 ...
Read now
Unlock full access