IntermediateLesson 9 of 156 min read

Traits and Generics: Shared Behaviour Without Inheritance

Define traits, implement them for several types, write generic functions with trait bounds, compare static and dynamic dispatch, and read the real compiler error for a missing bound.

In this lesson you will

  • Define and implement a trait
  • Write generic functions with bounds
  • Choose static or dynamic dispatch
  • Read the missing-bound error

About 28 minutes

Different sensors, one report

Ines’s farm has two kinds of sensor: an anemometer that measures wind speed in metres per second, and a thermometer that measures the temperature in degrees Celsius. She wants one report function that works with any sensor, and she does not want to put them in an inheritance tree, which Rust does not have. The answer is a trait, a named set of methods that a type promises to provide. A trait is similar to an interface in Java or C#, and unlike an interface it can be implemented for types you did not write, including built-in ones.

A generic function, written with a type parameter such as T, works with many types, and a trait bound such as T: Sensor limits it to those that implement the trait. For each concrete type the compiler generates a specialised copy, called monomorphisation, so the call is as fast as hand-written code and there is no run-time cost. This is static dispatch. When you need a collection of different types, such as a Vec of sensors, you use a trait object, Box, which looks up the method at run time through a table of function pointers, a small cost in return for flexibility. A trait can also provide default methods that implementers may override.

Concept Syntax Dispatch
Trait trait Sensor { fn read(&self) -> f64; } –
Implementation impl Sensor for Anemometer { … } –
Generic with bound fn report(s: &T) Static
impl Trait argument fn report(s: &impl Sensor) Static
Trait object Vec<Box> Dynamic
trait Sensor {
    fn name(&self) -> String;
    fn read(&self) -> f64;
    fn unit(&self) -> &str { "units" }
    fn summary(&self) -> String {
        format!("{}: {:.1} {}", self.name(), self.read(), self.unit())
    }
}

struct Anemometer { speed: f64 }
struct Thermometer { celsius: f64 }

impl Sensor for Anemometer {
    fn name(&self) -> String { "wind".to_string() }
    fn read(&self) -> f64 { self.speed }
    fn unit(&self) -> &str { "m/s" }
}

impl Sensor for Thermometer {
    fn name(&self) -> String { "temperature".to_string() }
    fn read(&self) -> f64 { self.celsius }
    fn summary(&self) -> String {
        format!("{} is {:.1} C ({:.1} F)", self.name(), self.celsius, self.celsius * 9.0 / 5.0 + 32.0)
    }
}

fn describe<T: Sensor>(s: &T) -> String { format!("generic: {}", s.summary()) }
fn loud(s: &impl Sensor) -> bool { s.read() > 10.0 }

fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
    let mut best = items[0];
    for &i in items { if i > best { best = i; } }
    best
}

fn main() {
    let a = Anemometer { speed: 12.34 };
    let t = Thermometer { celsius: 21.5 };
    println!("{}", describe(&a));
    println!("{}", describe(&t));
    println!("anemometer loud? {} | thermometer loud? {}", loud(&a), loud(&t));
    let all: Vec<Box<dyn Sensor>> = vec![Box::new(a), Box::new(t), Box::new(Anemometer { speed: 3.0 })];
    for s in all.iter() { println!("dyn: {}", s.summary()); }
    let total: f64 = all.iter().map(|s| s.read()).sum();
    println!("sum of readings (mixed units, only for demonstration): {:.2}", total);
    println!("largest int {} | largest float {} | largest char {}", largest(&[3, 9, 4]), largest(&[1.5, 0.2, 7.25]), largest(&['a', 'z', 'm']));
    println!("size of a Box<dyn Sensor>: {} bytes (pointer plus table)", std::mem::size_of::<Box<dyn Sensor>>());
}
generic: wind: 12.3 m/s
generic: temperature is 21.5 C (70.7 F)
anemometer loud? true | thermometer loud? true
dyn: wind: 12.3 m/s
dyn: temperature is 21.5 C (70.7 F)
dyn: wind: 3.0 m/s
sum of readings (mixed units, only for demonstration): 36.84
largest int 9 | largest float 7.25 | largest char z
size of a Box<dyn Sensor>: 16 bytes (pointer plus table)
fn largest<T>(items: &[T]) -> &T {
    let mut best = &items[0];
    for i in items {
        if i > best { best = i; }
    }
    best
}

fn main() {
    println!("{}", largest(&[3, 9, 4]));
}
error[E0369]: binary operation `>` cannot be applied to type `&T`
 --> m.rs:4:14
  |
4 |         if i > best { best = i; }
  |            - ^ ---- &T
  |            |
  |            &T
  |
help: consider restricting type parameter `T` with trait `PartialOrd`
  |
1 | fn largest<T: std::cmp::PartialOrd>(items: &[T]) -> &T {
  |             ++++++++++++++++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0369`.

Both sensors were used through the same trait. The anemometer relied on the default summary method, which builds a line from name, read and unit, and printed “wind: 12.3 m/s”, while the thermometer overrode summary to add a Fahrenheit value: “temperature is 21.5 C (70.7 F)”. The generic function describe and the impl-Trait function loud accept any type that implements Sensor, and the compiler generated a separate copy for each, so there is no dispatch cost. Both are above the limit of 10 (true and true), though the comparison is a little silly, since one value is metres per second and the other degrees: the trait lets the code treat them alike, and only a unit type would stop you from mixing them up.

To put different sensors into one vector, they were boxed as trait objects, and the loop printed three lines through dynamic dispatch. Each Box is a fat pointer of 16 bytes: one pointer to the data and one to the table of methods. The function largest has a bound of PartialOrd, to compare, and Copy, to return by value, and so works for integers (9), floats (7.25) and characters (z). The sum of the readings is only a demonstration of using the trait: it adds metres per second to degrees, which no real program should do, and that is the kind of mistake that types for units, such as a newtype struct, can prevent.

The second program removes the bound. Comparing two values of an unknown type T with a greater-than sign is error E0369, “binary operation > cannot be applied to type &T”, and the compiler explains that the type parameter T might not support comparison and suggests restricting it with std::cmp::PartialOrd. In C++ templates the equivalent error appears at the instantiation, often as a page of text. In Rust the bound is part of the function’s signature, so the error appears in the generic function itself, and a caller can read from the signature what a type must provide.

Check by hand: 21.5 x 9 / 5 + 32 = 38.7 + 32 = 70.7 degrees Fahrenheit, and 12.34 formats to 12.3 with one decimal. 12.34 + 21.5 + 3.0 = 36.84, which the program printed with two decimals. A fat pointer holds two 8-byte addresses, so it is 16 bytes on a 64-bit system.

Do not use dyn when generics will do

A trait object costs a pointer indirection and prevents some optimisations. Use generics or impl Trait for performance-critical code and a Vec<Box> only when you need a collection of mixed types.

Put the bound where it is needed

Write the weakest bound that makes the function compile. If you only compare, require PartialOrd. If you also need to copy, add Copy. The where clause keeps long bounds readable.

About this course

Every program in this lesson was compiled with rustc 1.97 (edition 2021) and run while the course was written. Rust releases every six weeks and its compiler messages improve all the time, so check doc.rust-lang.org for the current edition and wording. The pointer size of 16 bytes is for a 64-bit Linux system.

Practice

Add a third sensor, a Barometer, that uses all the default methods. Write a function that returns the sensor with the highest reading from a slice of Box. Replace the Copy bound in largest by Clone, and fix the code.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is a trait?

  1. A class
  2. A set of methods a type promises to provide
  3. A module
  4. A macro

Similar to an interface.

What is monomorphisation?

  1. A copy of a generic function per concrete type
  2. Dynamic dispatch
  3. A macro
  4. A lifetime

It gives static dispatch.

When do you need Box?

  1. A collection of different types
  2. Always
  3. Never
  4. For integers

Methods are looked up at run time.

What error appears if a generic function compares T without a bound?

  1. E0382
  2. E0499
  3. E0308
  4. E0369

Add PartialOrd.

Can a trait have default methods?

  1. No
  2. Only in generics
  3. Only for integers
  4. Yes, which implementers may override

As summary did.

Summary

  • A trait lists methods a type promises; default methods are optional.
  • Generic functions use bounds and are monomorphised, so there is no run-time cost.
  • Box gives dynamic dispatch for mixed collections.
  • Missing bounds are caught at the function signature.

Next lesson

Lesson 10 covers lifetimes.

Questions

Does Rust have inheritance?

No. Rust composes behaviour with traits and data with structs. Traits can require other traits, which gives something similar to interface inheritance.

Can I implement a trait for a built-in type?

Yes, if either the trait or the type is defined in your crate. This is called the orphan rule.

What is impl Trait?

Shorthand for a generic with a bound in argument position, and a way to return an unnamed type that implements a trait.

Progress is saved in this browser.