Implementing Traits

Implementing Traits in Rust: Somewhere there is a register that says which products meet which standards.

The Analogy: Who Is Allowed To Amend The Register

Somewhere there is a register that says which products meet which standards. Every line in it has three parts: a standard, a product, and the details of how that product satisfies it. Reading the register is how a buyer knows a cable is safe to install in a wall -- nobody re-tests anything, they look up the pair and trust the line.

Adding a line is the work. It is not a claim, it is a submission: the actual measurements, the actual method, the actual results filled in against every blank the standard left. That is what implementing means. The standard says a product of this kind must state its rated current and must survive a bend test; the submission says this cable is rated at thirteen amps and here is the bend result. Afterwards the register holds one concrete answer for that pair.

Only two parties may add a line for a given pair, and the rule is short: you must own one end of it. The standards body may certify any product, because the standard is theirs. A manufacturer may certify its own product against any published standard, because the product is theirs. Anyone else looking at that pair is a bystander with no standing.

The reason is not bureaucracy, it is arithmetic. If bystanders could file lines about other people's products against other people's standards, two bystanders could file contradictory lines for the same pair, and a reader would have no way to decide which one applies. One line per pair, written by one of the two parties with standing. And when you genuinely do need a product you do not own certified against a standard you do not own, the way through is to package it as a product of your own and certify that -- which has a name in Rust too, and appears later in this lesson.


Syntax or Core Structure

An implementation names a trait, names a type, and fills in the bodies:

use std::fmt;

struct Coord {
    east: i32,
    north: i32,
}

impl fmt::Display for Coord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}E {}N", self.east, self.north)
    }
}

fn main() {
    let a = Coord { east: 12, north: -4 };

    println!("{}", a);
    println!("{}", a.to_string().len());

    let joined = format!("[{a}]");
    println!("{joined}");
}

Output:

12E -4N
7
[12E -4N]

impl fmt::Display for Coord is the whole submission, and both names in it matter. Display is the standard -- it belongs to the standard library and declares exactly one required method, fmt. Coord is the product, and it is local to this crate, which is what gives this file the standing to write the line. The signature of fmt is not a choice; it is copied from the trait, down to the &mut fmt::Formatter<'_> and the fmt::Result return type.

The second line of output is the interesting one. Nothing here implemented to_string, and yet it works. The standard library contains a single implementation covering every Display type at once, so satisfying one trait quietly satisfied another. This is the real return on implementing standard traits: you write one method and a large amount of code you did not write starts accepting your type.

Once you implementYou also get, without writing itBecause
Display{} in every macro, and .to_string()One implementation of ToString covers all Display types
From<A> for Ba.into() producing a BOne implementation of Into covers all From pairs
FromStr"...".parse() at your typestr::parse is written against FromStr
PartialOrd<, >, <= and >=The operators are calls to trait methods
Ord.sort(), .max(), BTreeMap keysThose APIs require the trait and nothing more
Error with Display and DebugAcceptance by Box<dyn Error> and ?The conversion in Module 5 requires exactly those three
Iteratorfor loops and all of Module 7for desugars to Iterator calls

Technical Depth: Derive, By Hand, And Who Has Standing

What derive actually writes, and when it is wrong

#[derive(...)] generates an ordinary implementation from the shape of the type. For several traits that is exactly right:

#[derive(Debug, Clone, PartialEq, PartialOrd)]
struct Version {
    major: u32,
    minor: u32,
    patch: u32,
}

fn main() {
    let a = Version { major: 1, minor: 4, patch: 0 };
    let b = Version { major: 1, minor: 10, patch: 0 };
    let c = a.clone();

    println!("a       {:?}", a);
    println!("a == c  {}", a == c);
    println!("a <  b  {}", a < b);
    println!("b <  a  {}", b < a);
}

Output:

a       Version { major: 1, minor: 4, patch: 0 }
a == c  true
a <  b  true
b <  a  false

Derived PartialEq compares every field. Derived PartialOrd compares fields in declaration order, stopping at the first pair that differs, which is why 1.4.0 sorts before 1.10.0: major ties, then 4 is less than 10. That is the correct answer here, and it is correct by luck rather than by design -- the fields happened to be declared in the order that matters.

Change that order and the derive produces a compiling, wrong program with nothing to warn you:

#[derive(Debug, PartialEq, PartialOrd)]
struct Timestamp {
    minute: u32,
    hour: u32,
}

fn main() {
    let early = Timestamp { minute: 59, hour: 8 };
    let later = Timestamp { minute: 5, hour: 9 };

    println!("08:59 later than 09:05? {}", early > later);
}

Output:

08:59 later than 09:05? true

Minutes are declared first, so minutes decide the comparison, so 08:59 is reported as later than 09:05. The derive did exactly what it promised; the promise was just not the one this type needed. Write the comparison by hand whenever the ordering is not literally "fields, in the order I typed them":

use std::cmp::Ordering;

#[derive(Debug, PartialEq, Eq)]
struct Timestamp {
    minute: u32,
    hour: u32,
}

impl Ord for Timestamp {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.hour.cmp(&other.hour) {
            Ordering::Equal => self.minute.cmp(&other.minute),
            unequal => unequal,
        }
    }
}

impl PartialOrd for Timestamp {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

fn main() {
    let early = Timestamp { minute: 59, hour: 8 };
    let later = Timestamp { minute: 5, hour: 9 };

    println!("08:59 later than 09:05? {}", early > later);

    let mut times = vec![
        Timestamp { minute: 5, hour: 9 },
        Timestamp { minute: 0, hour: 8 },
        Timestamp { minute: 59, hour: 8 },
    ];

    times.sort();

    for t in &times {
        println!("{:02}:{:02}", t.hour, t.minute);
    }
}

Output:

08:59 later than 09:05? false
08:00
08:59
09:05

Two things in that code are conventions rather than requirements, and both matter. PartialOrd delegates to cmp rather than being derived, because a derived PartialOrd alongside a hand-written Ord would give two different answers to the same question. And the match on Ordering has a shorter idiomatic form -- self.hour.cmp(&other.hour).then(self.minute.cmp(&other.minute)) -- which reads as "hours, and if those tie, minutes", and extends to as many fields as you like.

.sort() came free the moment Ord existed, because the standard library's sort asks for nothing else.

Standing: the orphan rule

An impl Trait for Type block is accepted when the trait is local to your crate, or the type is local to your crate. If neither is local, the compiler refuses with E0117, saying that only traits defined in the current crate can be implemented for types outside it. Both legal directions are useful and it is worth being deliberate about which one you are using.

You ownYou may writeTypical use
The typeAny external trait for itDisplay, From, FromStr on your own structs
The traitIt, for any external typeAn extension trait adding a method to u32
NeitherNothingWrap the type first

The second row is the one people forget exists, and it is how a crate adds a method to a type it did not write:

trait Padded {
    fn padded(&self, width: usize) -> String;
}

impl Padded for u32 {
    fn padded(&self, width: usize) -> String {
        let mut s = self.to_string();

        while s.len() < width {
            s.insert(0, '0');
        }

        s
    }
}

impl Padded for String {
    fn padded(&self, width: usize) -> String {
        let mut s = self.clone();

        while s.len() < width {
            s.push(' ');
        }

        s
    }
}

fn main() {
    println!("[{}]", 42u32.padded(5));
    println!("[{}]", String::from("ok").padded(5));
}

Output:

[00042]
[ok   ]

Padded is local, so implementing it for u32 and String is entirely legal. The method is then callable with ordinary dot syntax on a primitive, which is why this pattern is called an extension trait. The one catch is scope: a caller in another module has to use the trait before the method is visible.

The way past the rule

When neither end is yours -- Display for Vec<String>, say -- you wrap the foreign type in a local one. A tuple struct with a single field is the usual shape, and the pattern is called a newtype:

use std::fmt;

struct Csv(Vec<String>);

impl fmt::Display for Csv {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, field) in self.0.iter().enumerate() {
            if i > 0 {
                write!(f, ",")?;
            }

            write!(f, "{field}")?;
        }

        Ok(())
    }
}

fn main() {
    let row = Csv(vec![
        String::from("bolt-m6"),
        String::from("500"),
        String::from("g"),
    ]);

    println!("{row}");
    println!("{} fields", row.0.len());
}

Output:

bolt-m6,500,g
3 fields

Csv is local, so the line may be filed. The cost is that Csv is not a Vec and has none of its methods: every use of the inner value goes through .0, or through methods you forward by hand. There is a trait that makes the forwarding automatic, Deref, and it belongs with the smart pointers in Module 8.

Notice the ? inside fmt. write! returns fmt::Result, formatting can fail, and the same operator from Module 5 works here for exactly the same reason it worked there.

From, and the conversion that arrives with it

struct Metres(f64);

struct Feet(f64);

impl From<Feet> for Metres {
    fn from(f: Feet) -> Metres {
        Metres(f.0 * 0.3048)
    }
}

fn main() {
    let m = Metres::from(Feet(10.0));
    let m2: Metres = Feet(100.0).into();

    println!("{:.4} m", m.0);
    println!("{:.2} m", m2.0);
}

Output:

3.0480 m
30.48 m

One implementation, two call styles. into() was never written here and never needs to be: implement From and the reverse direction appears, which is why the standard library's advice is to implement From and never Into.


Real World Example: A Money Type That Behaves Like A Built-In

Amounts of money should not be f64, and they should not be bare i64 either, because a bare integer will happily be added to a line number. The fix is a newtype over whole pence -- and then a set of implementations that make it behave the way i64 behaves, since i64 gets its own behaviour from exactly the same traits.

use std::fmt;
use std::ops::Add;
use std::str::FromStr;

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct Pence(i64);

impl fmt::Display for Pence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let sign = if self.0 < 0 { "-" } else { "" };
        let abs = if self.0 < 0 { -self.0 } else { self.0 };
        let text = format!("{}{}.{:02}", sign, abs / 100, abs % 100);

        f.pad(&text)
    }
}

impl fmt::Debug for Pence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Pence({})", self.0)
    }
}

impl From<i64> for Pence {
    fn from(n: i64) -> Pence {
        Pence(n)
    }
}

impl Add for Pence {
    type Output = Pence;

    fn add(self, other: Pence) -> Pence {
        Pence(self.0 + other.0)
    }
}

impl Default for Pence {
    fn default() -> Pence {
        Pence(0)
    }
}

impl FromStr for Pence {
    type Err = String;

    fn from_str(text: &str) -> Result<Pence, String> {
        let trimmed = text.trim();
        let negative = trimmed.starts_with('-');
        let digits = if negative { &trimmed[1..] } else { trimmed };

        let (whole, part) = match digits.find('.') {
            Some(i) => (&digits[..i], &digits[i + 1..]),
            None => (digits, "0"),
        };

        if part.len() > 2 {
            return Err(format!("{} has more than two decimal places", trimmed));
        }

        let pounds: i64 = match whole.parse() {
            Ok(n) => n,
            Err(_) => return Err(format!("{} is not a number", trimmed)),
        };

        let mut pennies: i64 = match part.parse() {
            Ok(n) => n,
            Err(_) => return Err(format!("{} is not a number", trimmed)),
        };

        if part.len() == 1 {
            pennies *= 10;
        }

        let total = pounds * 100 + pennies;

        Ok(Pence(if negative { -total } else { total }))
    }
}

fn main() {
    let inputs = ["12.50", "8", "-3.05", "0.9", "4.567", "lots", " 6.25 "];
    let mut running = Pence::default();

    for text in inputs {
        let shown = format!("{:?}", text);

        match text.parse::<Pence>() {
            Ok(p) => {
                running = running + p;
                println!("{:>8} -> {:>8} running {:>8}", shown, p, running);
            }
            Err(e) => println!("{:>8} !! {}", shown, e),
        }
    }

    let a = Pence::from(1999);
    let b: Pence = 199i64.into();

    println!("from    {} and {}", a, b);
    println!("debug   {:?}", a);
    println!("compare {} {} {}", a > b, a == Pence(1999), Pence::default() == Pence(0));
}

Output:

 "12.50" ->    12.50 running    12.50
     "8" ->     8.00 running    20.50
 "-3.05" ->    -3.05 running    17.45
   "0.9" ->     0.90 running    18.35
 "4.567" !! 4.567 has more than two decimal places
  "lots" !! lots is not a number
" 6.25 " ->     6.25 running    24.60
from    19.99 and 1.99
debug   Pence(1999)
compare true true true

Count what the call sites in main actually use: {}, {:?}, +, >, ==, .parse(), Pence::from, .into() and Pence::default(). Not one of those is a method defined on Pence. Each one is a language feature or a standard-library function reaching for a trait, finding an implementation, and using it. The type reads like a built-in because being a built-in is not how i64 earns + either -- it has an Add implementation, written the same way this one is.

FromStr is the highest-leverage line in the file. It is one method, and it makes str::parse work at this type, which in turn means everything Module 5 taught about Result, match, unwrap_or and ? now applies to money with no further work. Note the type Err = String; at the top of that block: that is an associated type being chosen by the implementation rather than by the trait, and parse reads it back to decide what the error half of its Result is. Note also that String is Module 5's known compromise -- honest here, wrong in a library.

The f.pad(&text) in the Display implementation deserves its own warning. The obvious way to write that method is write!(f, "{}{}.{:02}", sign, abs / 100, abs % 100), which compiles, produces identical output in every example above except the padded ones, and silently discards the width. {:>8} is not applied by the caller; it is delivered to the implementation through the Formatter, and write! never looks at it. Hand-written Display implementations that ignore width are extremely common, nothing warns about them, and the bug only shows up the day someone tries to line the values up in a column.

The limits are worth naming precisely. Add uses i64 addition, which panics on overflow in a debug build and wraps in a release build -- a money type in production should use checked_add and return an error, and this one does not. The -self.0 in Display overflows for i64::MIN for the same reason. The parser rejects "1,000.00" and cheerfully accepts "007.5", its error messages blame the whole input rather than the offending part, and "12." is reported as not a number even though the real complaint is a missing fraction. And there is no currency anywhere in the type, so adding a pounds amount to a euros amount compiles and produces a meaningless number, which is the sort of thing the type system could have caught and was not asked to.


Common Mistakes

  1. Implementing a foreign trait for a foreign type. impl fmt::Display for Vec<String> is rejected with E0117 no matter how reasonable the formatting is, because neither Display nor Vec belongs to your crate. The compiler is not being fussy: two crates could otherwise supply different Display implementations for the same type and a program depending on both would have no defensible answer. Wrap the type in a local newtype and implement it for that.
  1. Deriving PartialOrd on a struct whose field order is not the sort order. The derive compares fields top to bottom and stops at the first difference, so Timestamp { minute, hour } compares minutes first and reports 08:59 as later than 09:05. Nothing warns, the code compiles, and the bug surfaces as a wrongly sorted list much later. Check the declaration order every time you reach for that derive.
  1. Writing one trait that must both construct values and be used behind dyn. A trait containing fn new() -> Self cannot be used as &dyn Trait, because a trait object has no idea what Self is. The usual fix is to split it: put the constructor in one trait and the object-safe operations in another, so callers that build values require the first and callers that only use values require the second.
    trait Reading {
        fn value(&self) -> f64;
    }

    trait Sensor: Reading {
        fn zero() -> Self;
    }
  1. Ignoring the format spec in a hand-written Display. Using write!(f, "...") throws away any width, fill and alignment the caller asked for, so {:>8} becomes a no-op. Build the text and hand it to f.pad instead. This is the single most common defect in Display implementations and it produces no diagnostic at all.
  1. Hand-writing Ord while deriving PartialOrd. The two then disagree: < uses the derived field-order comparison and .sort() uses yours. Implement Ord and have partial_cmp return Some(self.cmp(other)).
  1. Implementing Into instead of From. Into arrives free once From exists, but not the other way round, so implementing Into gives you one of the two call styles instead of both. Write impl From<A> for B.
  1. Hand-writing PartialEq and deriving Hash. Two values that compare equal must hash equally, and a hand-written PartialEq that skips a field breaks that the moment the type is used as a HashMap key -- lookups miss for keys that are supposedly present. If one of PartialEq and Hash is written by hand, both must be.
  1. Forgetting to bring an extension trait into scope. The method exists, the implementation exists, and the call site still fails to compile, because a trait's methods are only visible where the trait is in scope. The error mentions the trait by name and the fix is a use.
  1. Parsing {:?} output. Derived Debug formatting is for people reading logs, not for machines. It is explicitly not a stable format, and adding a field silently changes it. Implement Display or a real serializer if something is going to read it back.

Best Practices

  • Derive Debug on essentially every type, and implement Display only where a human actually reads the value. Debug is a debugging aid and can be mechanical; Display is a product decision about wording.
  • Use f.pad(&text) in Display implementations rather than writing straight to the formatter, so callers can align your type in a table.
  • Derive when the generated semantics are what you want, and hand-write when they are not -- with a one-line comment saying why, so the next reader does not helpfully replace your implementation with a derive.
  • Implement From, never Into. Give the conversion a single home and let the standard library supply the other direction.
  • Implement FromStr for any type built from configuration, command-line arguments or a file, and the whole of parse and its error handling comes with it.
  • Reach for a newtype to cross the orphan rule, and forward the handful of inner methods you actually need instead of leaving .0 visible at every call site.
  • Keep PartialEq, Eq, Hash and Ord consistent with each other: derive them as a group or write them as a group, and make sure they agree about which fields count.
  • Prefer an extension trait over a free helper function when the dot-syntax call site reads better, and keep the trait in one obvious module so the required use is easy to find.

Practice Exercises

  1. Add Sub and Neg to Pence. Then add checked_sub and checked_neg methods returning Option<Pence>, and write a short note explaining why the Sub implementation itself cannot return an Option -- what does the trait's associated Output type let you choose, and what does the - operator then commit you to?
  1. Give Version a fourth field, pre_release: Option<String>, where a pre-release sorts before the released version with the same numbers, so 1.4.0-rc1 is less than 1.4.0. Show that no field ordering makes the derive produce this, then implement Ord and PartialOrd by hand using Ordering::then for the numeric part.
  1. Extend Csv so that any field containing a comma, a double quote or a newline is wrapped in double quotes with internal quotes doubled. Verify it with a row containing bolt, m6 and a row containing 13", then explain in two sentences why this had to be written for Csv and could not have been written for Vec<String>.
  1. Add a currency to the money type -- either Money { pence: i64, currency: Currency } with a runtime check in Add, or two separate newtypes Pounds and Euros so that mixing them fails to compile. Implement your choice, then write a paragraph on the trade: what does the compile-time version cost you when the currency is only known at runtime?