Skip to content
tezvyn:
Menu

Rust's Deref Trait: Smart Pointers Acting Like Data

Source: doc.rust-lang.orgMediumHow cards are made

The Deref trait lets a "smart pointer" type act like the data it contains, making wrappers transparent. It enables calling an inner type's methods directly on a wrapper, like using &str methods on a String. Its deref() method must never fail.

Why it exists

Rust uses wrapper types, or "smart pointers," to manage ownership and storage, like Box<T> or Rc<T>. Without a special mechanism, accessing the inner data T would require verbose syntax like my_box.inner.some_method(). The Deref trait was created to make these wrappers ergonomic, allowing them to behave like the data they hold.

The mental model

Think of Deref as a one-way lens. It lets a wrapper type, like String, provide a transparent "view" into its underlying data, str. The compiler automatically looks through this lens for you when you try to call a method, a mechanism called "Deref coercion." This makes the wrapper feel like the value it contains.

How it works

To use it, you implement trait Deref for your type. This requires defining one method, deref(&self), which must return a reference to the inner data (&Self::Target). When the compiler sees you call a method on a reference to your wrapper (&MyWrapper) that only exists on the inner type (&InnerData), it silently inserts a call to .deref() to convert the types and make the call succeed.

When to use it

Implement Deref when your type is a true smart pointer that transparently manages another value. The key is that the wrapper should behave just like the inner value in most contexts, and the deref() operation must be computationally cheap. This is for types that are fundamentally pointers-in-disguise.

When not to use it

The biggest footgun is fallibility. The deref() method should never panic, because the compiler calls it implicitly in many places, and a hidden panic is extremely difficult to debug. Also, avoid implementing Deref if your wrapper type has methods that could clash with the inner type's methods; this is why Box<T> has almost no methods of its own. Finally, implementing Deref is a very strong public API commitment that you cannot easily take back.

One canonical example

The relationship between String and str is the classic case. String is an owned, heap-allocated buffer. It implements Deref<Target = str>. This allows you to call any &str method (like .len(), .lines(), or .trim()) directly on a String value, because the compiler automatically coerces &String into &str for you.

Interview question

When is it most appropriate to implement the Deref trait for a custom type in Rust?

  • a.To allow a wrapper type to expose a subset of its inner type's methods, controlling access.
  • b.When your type is a transparent smart pointer that should behave identically to its inner value, and dereferencing is infallible.Correct
  • c.When you need to provide custom logic for accessing an inner value, even if that access might fail or be expensive.
  • d.To enable implicit type conversions between any two related types, simplifying function signatures.
Why?

Option B accurately describes the ideal scenario for Deref: a transparent smart pointer that acts like its inner data, with an infallible dereference operation. Option A is incorrect because Deref aims for full transparency, not selective exposure or control over a subset of methods.

Just read this? Test yourself on what you have been reading.

Read the original → doc.rust-lang.org

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on rust — each one lists the topics its interview covers.

See open roles