typestar

Deref on a newtype in Rust

Deref lets a wrapper forward the inner type's methods without writing any.

use std::ops::Deref;

struct Handle(String);

impl Deref for Handle {
    type Target = String;

    fn deref(&self) -> &String {
        &self.0
    }
}

fn main() {
    let handle = Handle("ada_lovelace".to_string());
    println!("{}", handle.len());
    println!("{}", handle.to_uppercase());
    println!("{}", handle.starts_with("ada"));
    println!("{}", *handle);
}

How it works

  1. deref returns a reference to the wrapped value.
  2. Method calls then reach through the wrapper.
  3. Use it for smart pointers and newtypes, not for inheritance.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
334
Tokens
111
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 63 seconds.

Type this snippet

Step 3 of 4 in Operators & access, step 14 of 19 in Traits & generics.

← Previous Next →