Deref & Deref Coercion
Deref maps smart pointer to inner reference. Deref coercion converts &T to &U when T: Deref<Target=U> at call sites.
Search across all documentation pages
Deref maps smart pointer to inner reference. Deref coercion converts &T to &U when T: Deref<Target=U> at call sites.
use std::ops::Deref;
struct MyString(String);
impl Deref for MyString {
type Target = str;
fn deref(&self) -> &str { &self.0 }
}
fn print_len(s: &str) { println!("{}", s.len()); }
fn main() {
let s = MyString("hello".into());
print_len(&s); // coercion &MyString -> &str
}When to reach for this: Newtype wrappers and smart pointers acting like inner type.
fn main() {
let s = String::from("rust");
let len = str_len(&s);
println!("{len}");
}
fn str_len(s: &str) -> usize { s.len() }What this demonstrates:
&String coerces to &str via DerefBox<T>, Rc<T> similarly coerce when T: DerefDeref coercion chain limited to avoid infinite recursion. DerefMut for mutable coercion.
Deref clones. Fix: impl Deref to inner ref only.*box explicit deref.
| Alternative | Use When | Don't Use When |
|---|---|---|
AsRef trait | Explicit conversion intent | Deref ergonomics wanted |
.as_str() method | Clear conversion | Coercion magic ok |
| Borrow trait | Hash map keys | General param coercion |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Reviewed by Chris St. John·Last updated Jul 19, 2026