Start with the idea
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.
Keep learning, for free
The rest of this lesson is waiting for you.
Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.
No payment details. Your account opens the complete Academy.