trait

Rust Deref

Deref lets a pointer-like wrapper expose a borrowed target through * and appropriate coercions. Implement it when the wrapper should transparently behave like its target; it changes method lookup and public API behavior. Keep the operation unsurprising and cheap. Expected output (not executed): label: desk Why: The function argument coerces &Text to &str using Deref. Common mistake: Using Deref merely to expose unrelated convenience methods.

Formal Syntax & Structure

rust syntaxrust
trait Deref { type Target: ?Sized; fn deref(&self) -> &Self::Target; }

Working Example

Example Snippetrust
use std::ops::Deref;struct Text(String);impl Deref for Text {    type Target = str;    fn deref(&self) -> &str { &self.0 }}fn label(s: &str) { println!("label: {s}"); }fn main() { let t = Text("desk".into()); label(&t); }
Rust Reference