Expand description
Used for mutable dereferencing operations, like in *v = 1;
.
In addition to being used for explicit dereferencing operations with the
(unary) *
operator in mutable contexts, DerefMut
is also used implicitly
by the compiler in many circumstances. This mechanism is called
‘Deref
coercion’. In immutable contexts, Deref
is used.
Implementing DerefMut
for smart pointers makes mutating the data behind
them convenient, which is why they implement DerefMut
. On the other hand,
the rules regarding Deref
and DerefMut
were designed specifically to
accommodate smart pointers. Because of this, DerefMut
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 DerefMut
is invoked
implicitly.
More on Deref
coercion
If T
implements DerefMut<Target = U>
, and x
is a value of type T
,
then:
- In mutable contexts,
*x
(whereT
is neither a reference nor a raw pointer) is equivalent to*DerefMut::deref_mut(&mut x)
. - Values of type
&mut T
are coerced to values of type&mut U
T
implicitly implements all the (mutable) 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 modifiable by dereferencing the struct.
use std::ops::{Deref, DerefMut};
struct DerefMutExample<T> {
value: T
}
impl<T> Deref for DerefMutExample<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl<T> DerefMut for DerefMutExample<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.value
}
}
let mut x = DerefMutExample { value: 'a' };
*x = 'b';
assert_eq!('b', x.value);