FerrousPath

Level 2 · Practitioner· Lesson 2 of 8 · 30 min

Traits

Shared behaviour without inheritance — defining, implementing and deriving traits, and the standard traits every Rust programmer knows.

Defining and implementing a trait

A trait is a set of methods a type can implement. It is Rust’s mechanism for shared behaviour and for constraining generics.

trait Describe {
    // Required: implementors must provide it.
    fn name(&self) -> String;

    // Provided: a default that implementors may override.
    fn describe(&self) -> String {
        format!("This is {}.", self.name())
    }
}

struct Dog;
struct Robot { model: u32 }

impl Describe for Dog {
    fn name(&self) -> String {
        "a dog".to_string()
    }
}

impl Describe for Robot {
    fn name(&self) -> String {
        format!("robot #{}", self.model)
    }
    fn describe(&self) -> String {
        format!("BEEP. I AM {}.", self.name().to_uppercase())
    }
}

fn introduce(thing: &impl Describe) {
    println!("{}", thing.describe());
}

fn main() {
    introduce(&Dog);
    introduce(&Robot { model: 7 });
}

There is no inheritance. Types do not form hierarchies; they implement capabilities.

Traits as bounds

These three signatures mean the same thing:

use std::fmt::Display;

fn a(x: impl Display) { println!("{x}"); }
fn b<T: Display>(x: T) { println!("{x}"); }
fn c<T>(x: T) where T: Display { println!("{x}"); }

fn main() {
    a(1); b("two"); c(3.0);
}

impl Trait in return position is different: it says “I return some single concrete type that implements this trait, and I am not telling you which”.

fn evens(limit: u32) -> impl Iterator<Item = u32> {
    (0..limit).filter(|n| n % 2 == 0)
}

fn main() {
    println!("{:?}", evens(10).collect::<Vec<_>>());
}

The real type here is an unwieldy nest of adapters, and closures have types that cannot be written at all. impl Trait lets you return them.

The orphan rule

You can implement a trait for a type only if your crate defines the trait or the type. You may implement your Describe for Vec<i32>, or Display for your Robot, but not Display for Vec<i32>. Without this rule, two libraries could each implement the same trait for the same type and no program could use both. The workaround is the newtype pattern: wrap the foreign type in your own struct.

Operator overloading and standard traits

Operators are trait methods. a + b calls Add::add(a, b).

use std::fmt;
use std::ops::Add;

#[derive(Debug, Clone, Copy, PartialEq, Default)]
struct Vec2 {
    x: f64,
    y: f64,
}

impl Add for Vec2 {
    type Output = Vec2;
    fn add(self, o: Vec2) -> Vec2 {
        Vec2 { x: self.x + o.x, y: self.y + o.y }
    }
}

impl fmt::Display for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

impl From<(f64, f64)> for Vec2 {
    fn from((x, y): (f64, f64)) -> Self {
        Vec2 { x, y }
    }
}

fn main() {
    let a = Vec2 { x: 1.0, y: 2.0 };
    let b: Vec2 = (0.5, 0.5).into(); // Into comes free with From
    println!("{} {:?} {}", a + b, Vec2::default(), a == b);
}

The traits worth knowing by heart:

Trait Gives you Derivable
Debug {:?} formatting yes
Display {} formatting and .to_string() no
Clone .clone() yes
Copy implicit bitwise copy instead of move yes
PartialEq, Eq ==; Eq adds “equality is total” yes
PartialOrd, Ord <, sorting; Ord is a total order yes
Hash use as a HashMap key yes
Default T::default() yes
From / Into infallible conversion no
TryFrom / TryInto fallible conversion no
AsRef<T> cheap borrow as another type no
Iterator for loops and all adapters no
Drop custom cleanup no

f64 is PartialEq but not Eq, and PartialOrd but not Ord, because NaN != NaN. That is why you cannot sort floats with plain .sort() or use them as map keys.

Associated types and constants

trait Shape {
    const SIDES: u32;
    type Unit;
    fn perimeter(&self) -> Self::Unit;
}

struct Square(f64);

impl Shape for Square {
    const SIDES: u32 = 4;
    type Unit = f64;
    fn perimeter(&self) -> f64 {
        self.0 * Self::SIDES as f64
    }
}

fn main() {
    println!("{} sides, perimeter {}", Square::SIDES, Square(2.5).perimeter());
}

An associated type is chosen by the implementor, once per implementation. Iterator::Item is the canonical example.

Supertraits and blanket implementations

use std::fmt::Display;

// Anything implementing Loud must also implement Display.
trait Loud: Display {
    fn shout(&self) -> String {
        self.to_string().to_uppercase() + "!"
    }
}

// Blanket implementation: every Display type is Loud.
impl<T: Display> Loud for T {}

fn main() {
    println!("{} {}", "hello".shout(), 42.shout());
}

Blanket implementations are how ToString is available on everything that implements Display. An extension trait like Loud is the idiomatic way to add methods to types you do not own.

Exercises

  1. Define a trait Area and implement it for Circle and Rect. Write fn total_area(shapes: &[impl Area]) -> f64. Why can the slice not mix circles and rectangles? (Level 3 answers this.)
  2. Implement Display and From<&str> (parsing "3,4"; panic on bad input) for Vec2.
  3. Derive PartialOrd on a struct with two fields and discover by experiment how the comparison is defined.
Answer to 3

Derived ordering is lexicographic in field declaration order: compare the first field, and only if equal compare the second. For enums, earlier variants are smaller.

Check your understanding

Pick an answer to see the explanation.

  1. 1.What does the orphan rule require for impl Trait for Type?

  2. 2.What does impl Trait mean in argument position, as in fn f(x: impl Display)?

  3. 3.Which trait do you implement to get .into() for free?

Key terms in this lesson

Finished the lesson and the exercises?