How to Use the Deref and DerefMut Traits in Rust

Implement Deref and DerefMut traits to make custom smart pointers behave like standard references for reading and mutating data.

Implement Deref to treat a custom type like a reference and DerefMut to allow mutable access through the dereference operator.

use std::ops::{Deref, DerefMut};

struct MyBox<T>(T);

impl<T> MyBox<T> {
    fn new(x: T) -> MyBox<T> { MyBox(x) }
}

impl<T> Deref for MyBox<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target { &self.0 }
}

impl<T> DerefMut for MyBox<T> {
    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
}

fn main() {
    let mut x = MyBox::new(5);
    println!("{}", *x); // Uses Deref
    *x = 10; // Uses DerefMut
    println!("{}", *x);
}