trait

Rust DerefMut

DerefMut extends Deref with mutable access to the same target type. Only implement it if exposing arbitrary target mutation preserves the wrapper invariants. It needs exclusive access to the wrapper, not just a shared reference. Expected output (not executed): 17 Why: The assignment uses mutable dereferencing to modify the contained integer. Common mistake: Implementing DerefMut on a validated value whose invariants arbitrary mutation could break.

Formal Syntax & Structure

rust syntaxrust
trait DerefMut: Deref { fn deref_mut(&mut self) -> &mut Self::Target; }

Working Example

Example Snippetrust
use std::ops::{Deref, DerefMut};struct Counter(u32);impl Deref for Counter {    type Target = u32;    fn deref(&self) -> &u32 { &self.0 }}impl DerefMut for Counter {    fn deref_mut(&mut self) -> &mut u32 { &mut self.0 }}fn main() { let mut n = Counter(10); *n += 7; println!("{}", *n); }
Rust Reference