Expand description
Used for immutable dereferencing operations, like *v.
In addition to being used for explicit dereferencing operations with the
(unary) * operator in immutable contexts, Deref is also used implicitly
by the compiler in many circumstances. This mechanism is called
‘Deref coercion’. In mutable contexts, DerefMut is used.
Implementing Deref for smart pointers makes accessing the data behind them
convenient, which is why they implement Deref. On the other hand, the
rules regarding Deref and DerefMut were designed specifically to
accommodate smart pointers. Because of this, Deref should only be
implemented for smart pointers to avoid confusion.
For similar reasons, this trait should never fail. Failure during
dereferencing can be extremely confusing when Deref is invoked implicitly.
More on Deref coercion
If T implements Deref<Target = U>, and x is a value of type T, then:
- In immutable contexts,
*x(whereTis neither a reference nor a raw pointer) is equivalent to*Deref::deref(&x). - Values of type
&Tare coerced to values of type&U Timplicitly implements all the (immutable) methods of the typeU.
For more details, visit the chapter in The Rust Programming Language as well as the reference sections on the dereference operator, method resolution and type coercions.
Examples
A struct with a single field which is accessible by dereferencing the struct.
use std::ops::Deref;
struct DerefExample<T> {
value: T
}
impl<T> Deref for DerefExample<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.value
}
}
let x = DerefExample { value: 'a' };
assert_eq!('a', *x);Run