liveBook · Manning

Deref

As explained in Learn Rust in a Month of Lunches

Deref is the Rust standard trait that defines immutable dereferencing and enables automatic dereference coercions for method and field access.

Deref lets a type act like a reference to a value it holds. Implementing it allows the `*` operator to reach that value and lets method calls find methods on the held type. This is useful for a wrapper that adds its own behavior without exposing its inner field directly. section 15.3.1 section 15.3.2 section 15.3

From a compiler error to a dereference

Suppose `HoldsANumber(u8)` contains `20`. Unlike a `Box`, it cannot initially be used as `*my_number`: the compiler says `HoldsANumber` cannot be dereferenced. Implementing `Deref` fixes that. Set `type Target = u8`, then make `deref(&self)` return `&self.0`. Now `*my_number + 20` produces `40` without writing `my_number.0`. section 15.3.1 section 15.3.2

use std::ops::Deref;
 
struct HoldsANumber(u8);
 
impl HoldsANumber {
    fn prints_the_number_times_two(&self) {
        println!("{}", self.0 * 2);
    }
}
 
impl Deref for HoldsANumber {
    type Target = u8;
 
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
 
fn main() {
    let my_number = HoldsANumber(20);
    println!("{:?}", my_number.checked_sub(100));   #1
    my_number.prints_the_number_times_two();        #2
}

The complete example puts an original method on `HoldsANumber` and uses `checked_sub()` from the inner `u8`. The call returns `None` when subtracting 100 from 20 would go below the range of `u8`. section 15.3.2

Deref provides immutable access, not permission to change the inner value. Even with `let mut my_number`, assigning through `*my_number` fails; the compiler points to `DerefMut` as the missing trait. section 15.3.2

Use Deref when the type really behaves like a smart pointer to its target. Making a game character dereference to its hit-point number may compile, but `*character` hides what the operation means. A named method such as `get_hp()` or `change_hp()` is clearer. section 15.3.4

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works through a Deref implementation, method calls, and compiler errors, then distinguishes immutable dereferencing from DerefMut.
Examples
Uses a number-holding tuple struct, Box comparison, checked subtraction, and a confusing game-character implementation.
What it assumes
Assumes familiarity with references, tuple structs, and methods while explaining Deref through small examples and compiler feedback.
What you can do after
Build it from scratch for a simple wrapper, access its target’s methods, and recognize when named methods are clearer.
How it connects
Connects Deref to newtypes, smart pointers, method access, and DerefMut.

Also explained in

Compare how 2 books explain Deref →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.