Rust Reference ยท Core Traits
The Deref and DerefMut traits
Reference for the Rust Deref and DerefMut traits: the * operator, deref coercion from &String to &str, building smart pointers, and the Deref polymorphism trap.
Deref customizes what the unary * operator does and, more importantly, enables deref coercion: when a function expects &str and you hold a &String, or expects &[T] and you hold a &Vec<T>, the compiler inserts the deref calls for you. Method calls use the same mechanism to find methods on the pointee, so boxed_string.len() works.
DerefMut is the mutable counterpart. Smart pointers (Box<T>, Rc<T>, Arc<T>, String, Vec<T>, MutexGuard<T>, Ref<T>) all implement Deref.
let s = String::from("hi"); let r: &str = &s; // &String coerces to &str via Deref
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub trait Deref { type Target: ?Sized; fn deref(&self) -> &Self::Target; } pub trait DerefMut: Deref { fn deref_mut(&mut self) -> &mut Self::Target; }
| Name | Description |
|---|---|
Target |
The type you get after dereferencing. It may be unsized (str, [T], dyn Trait). |
&self / &mut self |
The pointer; return a reference to the pointee inside it. |
Returns: a reference to Target. The call must be cheap, must not fail and must not do surprising side effects, because the compiler may insert it anywhere.
Usage notes
*xmeans*Deref::deref(&x)in a read context and*DerefMut::deref_mut(&mut x)in a write context. For&TandBox<T>the compiler handles*natively, and moving out with*boxedis only allowed forBox.- Deref coercion converts
&Uto&TwhenU: Deref<Target = T>, repeatedly if needed, and&mut Uto&mut TwithDerefMut. It also converts&mut Tto&T. It only happens at coercion sites such as function arguments,letwith a type annotation and struct fields, not in generic bounds likeT: AsRef<str>. - Method lookup auto-derefs.
rc.len()triesRc<String>, thenString, thenstr. This is why smart pointers feel transparent. - Only for pointer-like types. Using
Derefto fake inheritance (impl Deref for Dog { Target = Animal }) is an anti-pattern: it leaks every method, confuses trait resolution and surprises readers. Prefer composition with explicit forwarding or a trait. - Fields are not hidden: a wrapper with
Derefexposes the target's methods, but your own methods win when names clash, and the target's associated functions (T::new) are not forwarded. - Associated functions of the pointer should not be methods.
Rc::clone(&a)is written that way soa.clone()keeps meaning "clone the pointee" when it is ambiguous. Follow that style in your smart pointers. - Unrelated to
Drop. A smart pointer typically implements both:Dereffor access andDropfor cleanup. - Alternatives:
AsReffor explicit, multi-target views;Borrowwhen lookups must stay consistent.