Sub topic 17
The newtype pattern
This chapter assumes you can define tuple structs, write impl blocks, and use Display and privacy as covered earlier in the tutorial.
What a newtype is
A newtype is a tuple struct with exactly one field. It wraps an existing type and gives it a new, distinct identity.
struct Meters(f64);
struct Feet(f64);Both types hold an f64, but the compiler treats them as unrelated. The wrapper adds no runtime cost. The compiler stores a Meters exactly as it stores an f64.
Use 1: stop mixing up values
Primitive types say nothing about what a value means. A function that takes two f64 arguments accepts them in either order. A newtype moves that check to compile time.
struct Meters(f64);
struct Feet(f64);
impl Feet {
fn to_meters(&self) -> Meters {
Meters(self.0 * 0.3048)
}
}
fn describe(distance: &Meters) -> String {
format!("{:.1} m", distance.0)
}
fn main() {
let run = Feet(100.0);
// describe(&run); // error: expected `&Meters`, found `&Feet`
println!("{}", describe(&run.to_meters()));
}The conversion has to be explicit, so a unit mistake becomes a compile error. You reach the inner value with .0.
Use 2: implement a trait for a type you don't own
Rust's orphan rule says you can implement a trait for a type only if your crate defines the trait or the type. You can't implement Display for Vec<String>, because the standard library owns both. Wrapping the Vec in your own struct gets around this.
use std::fmt;
struct Names(Vec<String>);
impl fmt::Display for Names {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}]", self.0.join(", "))
}
}
fn main() {
let names = Names(vec!["Ada".to_string(), "Grace".to_string()]);
println!("{}", names);
}Use 3: enforce an invariant
Combine a newtype with a private field and the type can only be built through your constructor. Any value of that type has then passed validation.
mod email {
#[derive(Debug, Clone, PartialEq)]
pub struct Email(String);
impl Email {
pub fn parse(input: &str) -> Result<Self, String> {
if input.contains('@') {
Ok(Self(input.to_string()))
} else {
Err(format!("invalid email: {input}"))
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
}
use email::Email;
fn main() {
match Email::parse("[email protected]") {
Ok(e) => println!("ok: {}", e.as_str()),
Err(msg) => println!("{msg}"),
}
println!("{:?}", Email::parse("nope"));
}The field in pub struct Email(String) has no pub, so code outside the module can't write Email("nope".into()). A function that takes an &Email can skip re-checking the input.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Meters` can't be printed or compared | A newtype inherits none of the inner type's traits | Add `#[derive(Debug, Clone, PartialEq)]` or implement the traits |
| `a + b` fails on two `Meters` | Operators belong to the inner type | Implement `std::ops::Add` for the wrapper |
| `names.len()` fails on `Names` | Methods of the inner type are not forwarded | Write a `len` method that calls `self.0.len()` |
Exercise
Why does impl fmt::Display for Vec<String> fail to compile in your own crate, and how does a newtype fix it?
Show answer
The orphan rule requires your crate to define either the trait or the type, and the standard library defines both Display and Vec. Wrapping the vector in struct Names(Vec<String>); creates a type your crate owns, so you can implement Display for it.