Deref is a #202204061235 that allows the dereferencing of a #data-structure or an enum
. It is especially useful in #202111301656. All structures that implement the trait Deref must have the method deref
implemented into them. This is shown as follow:
use std::ops::Deref;
impl<T> Deref for MyStruct<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0 // Assume MyStruct is a single element tuple
}
}
Note: The method deref
shall return a reference. This is to enforce an implicit Deref coercion that will be explained below.
In Rust, there is a policy called Deref coercion. What it does is converts a reference to a type into a reference to another type. For example, Rust will convert &String
to &str
using &String
deref
method which return a &str
. This policy will be enforced when the reference to a particular type is passed as a function or method argument, but it doesn’t match the required or defined parameter type. Then, Rust will continuously call the deref
method down the chain until it can satisfy the requirement, otherwise it will raise a compile error.
There are some restrictions though. Mutable reference (&mut T
with DerefMut
) can be converted into both mutable reference and immutable reference (&T
with Deref
). An immutable reference can only be converted into another immutable reference.