Smart Pointers · 16 min · free lesson

Deref & Drop

Deref makes your type usable like a reference to another one.

Core idea

Deref coercion applies repeatedly until the types line up.

Diagram for Deref & Drop: a Rust code example flows to the lesson rule and the key observation.
Deref coercion is why &MyBox<String> reaches a &str parameter.

Understand it

Implementing Deref lets the compiler insert conversions automatically, which is why &String works where &str is expected. Drop lets a type run code when it goes out of scope, and the two together are how smart pointers feel built in — a Box behaves like the value it holds and cleans up on its own.

Deref tells Rust how a pointer-like wrapper exposes a reference to its target. In the example, MyBox<T> can return &T from its inner field, so code can read the wrapped value through familiar syntax. Deref coercion can adapt &String to &str through the type's implementations. This convenience should be predictable: implementing Deref for a type that is not really pointer-like can make method resolution and ownership harder to understand.

Drop describes cleanup when an owner leaves scope. A wrapper around a file or other resource can release it in drop, and the caller does not need to remember an explicit cleanup line on every path. You cannot normally call a value's drop method directly; std::mem::drop(value) consumes it and triggers cleanup early. A moved wrapper is dropped by its new owner, not again at the old binding.

Build a small wrapper, implement Deref, and call a method from the inner type through it. Then add a Drop implementation that logs when cleanup happens. Place one wrapper in an inner block and predict the log order. Keep the wrapper's behavior unsurprising: Deref for transparent access, Drop for resource cleanup. If the wrapper needs complex policy or fallible access, explicit methods often communicate more clearly than pretending it is the target value.

Remember that Drop::drop receives &mut self, so it can inspect and release fields but cannot move arbitrary fields out as if the object were still complete. The compiler still drops fields after the method returns. Avoid panicking in destructors, especially during unwinding, and keep cleanup as reliable as possible.

Test the exact point where each wrapper leaves scope.

Read the code

use std::ops::Deref;

struct MyBox<T>(T);

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

fn greet(name: &str) { println!("hello {name}"); }

let boxed = MyBox(String::from("ada"));
greet(&boxed); // &MyBox<String> -> &String -> &str

Deref coercion is why &MyBox<String> reaches a &str parameter.

Practice starter

struct Guard;

impl Drop for Guard {
    fn drop(&mut self) { println!("released"); }
}

fn main() {
    let _guard = Guard;
    println!("working");
}

Practise this code in Playground ↗

Try it

Implement Deref for a wrapper and pass it where the inner type is expected.

What success looks like: The call compiles without an explicit conversion.

Check your understanding

When does that Drop message print?

Reveal the answer
  1. Only when you call drop() on it explicitly
  2. Automatically when the value leaves scope
  3. At program exit, once main has returned

Drop runs at the end of the value's scope; std::mem::drop just ends it sooner.

Go deeper

Common misconception: “Cleanup runs only if you call drop on a value yourself.”

Drop runs automatically when the owner leaves scope. std::mem::drop only ends that scope sooner.

  1. Read the impl: Deref for MyBox<T> sets Target = T, and deref returns &self.0, a reference to the wrapped value.
  2. Follow the coercion: greet(&boxed) passes &MyBox<String>. The compiler applies MyBox's deref to get &String, then String's to get &str.
  3. See the call: No conversion appears at the call site, and the function prints hello ada. Coercion stops as soon as the types line up.

Transfer challenge: Add a Drop impl to MyBox<T> that prints a line, then create a second MyBox in an inner block. Predict the order of hello and each drop line before running it.

Connections

  • Rc & RefCell: Shared ownership and interior mutability
  • Reference Cycles: Weak<T> and leaks Rust cannot prevent
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Deref & Drop (courseId "projects", lessonId "deref-drop")
Link: https://crabrix.com/learn/projects/deref-drop/
Goal: Deref coercion applies repeatedly until the types line up.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=projects/deref-drop) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.