DEV Community

Cover image for Rust: Transparent Wrappers with Deref Coercion
Anton Dolganin
Anton Dolganin

Posted on

Rust: Transparent Wrappers with Deref Coercion

The Newtype pattern (struct Username(String)) is great for type safety, but it often feels clunky because you lose direct access to the inner type's methods. Implementing the Deref trait solves this, making your wrapper behave like the data it holds.

Why Use It

  1. Zero-Cost Abstraction: Strict type differentiation (e.g., Username vs. Password) without the boilerplate of proxying every method.
  2. API Ergonomics: Seamlessly use methods like .len(), .is_empty(), or .contains() directly on your custom struct.

Implementation


use std::ops::Deref;

struct Username(String);

impl Deref for Username {
    type Target = str; // The type we want to "mimic"

    fn deref(&self) -> &Self::Target {
        &self.0 // Return a reference to the inner value
    }
}
Enter fullscreen mode Exit fullscreen mode

In Action

Thanks to Deref Coercion, the compiler automatically triggers .deref() when it encounters a type mismatch that can be resolved by a reference.


let name = Username("Anton".to_string());

// 1. Direct access to &str methods
println!("{}", name.len());        
println!("{}", name.contains("a")); 

// 2. Passing to functions expecting &str
fn greet(s: &str) {
    println!("Hello, {s}");
}

greet(&name); // Coercion kicks in here
Enter fullscreen mode Exit fullscreen mode

Intent Matters: Only use this when the wrapper is conceptually a “smart pointer” or a transparent extension. If the inner type’s methods could break your struct’s internal logic, stick to manual method delegation.

Top comments (0)