Sub topic 1
Quick recap: traits and generic bounds
This chapter refreshes the trait and bound syntax that the rest of the tutorial builds on. It sets up the question that associated types answer: how does a trait refer to a type that each implementer chooses?
Prerequisites
This chapter assumes you can already do the following:
- Define a trait and implement it for a struct.
- Write a generic function with a trait bound.
- Read basic lifetime annotations such as
&'a T. - Use
Iteratorin aforloop and with adapters likemapandfilter.
If any of these is unfamiliar, review it first. The later chapters use all of them without re-explaining.
A trait is a set of required items
A trait names behavior that a type can provide. So far, the items you have likely used are methods. A trait can also declare other items, and this tutorial is about one of them: associated types.
trait Shape {
fn area(&self) -> f64;
fn describe(&self) -> String {
format!("shape with area {:.2}", self.area())
}
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn main() {
println!("{}", Square(3.0).describe());
}area is required, so every implementer must write it. describe has a default body, so implementers get it for free and may override it. The program prints shape with area 9.00.
Bounds restrict generic code
A generic function works for many types. A bound limits which types are allowed, and it also tells the compiler which methods the function may call.
use std::fmt::Display;
fn show_twice<T: Display>(value: T) -> String {
format!("{value} {value}")
}
fn largest<T>(items: &[T]) -> &T
where
T: PartialOrd,
{
let mut best = &items[0];
for item in items {
if item > best {
best = item;
}
}
best
}
fn main() {
println!("{}", show_twice("hi"));
println!("{}", largest(&[3, 9, 4]));
}The two spellings, T: Display inline and a where clause, mean the same thing. Use where when bounds get long or involve several type parameters. You can combine bounds with +, as in T: Display + Clone.
Without the PartialOrd bound, the comparison item > best would not compile, because the compiler knows nothing about T.
Traits can have generic parameters
A trait can itself take type parameters. From is the standard example: From<T> says "I can be built from a T".
struct Celsius(f64);
struct Fahrenheit(f64);
impl From<Celsius> for Fahrenheit {
fn from(c: Celsius) -> Self {
Fahrenheit(c.0 * 9.0 / 5.0 + 32.0)
}
}
fn main() {
let f = Fahrenheit::from(Celsius(100.0));
println!("{}", f.0);
}This prints 212. A single type may implement From<T> several times with different T. That is possible because From<Celsius> and From<i32> are different traits as far as the compiler is concerned.
The gap this tutorial fills
Suppose you want a trait for containers, with a method that returns the first element. The element type depends on the container, so the trait needs some way to mention it. One option is a generic parameter:
trait Container<Item> {
fn first(&self) -> Option<&Item>;
}
struct Stack<T> {
items: Vec<T>,
}
impl<T> Container<T> for Stack<T> {
fn first(&self) -> Option<&T> {
self.items.first()
}
}
fn main() {
let s = Stack { items: vec![1, 2, 3] };
println!("{:?}", s.first());
}This compiles and runs, and it prints Some(1). The cost shows up in generic code. Any function that accepts a Container must also name the item type, even when the caller has no say in it:
fn peek<C, Item>(c: &C) -> Option<&Item>
where
C: Container<Item>,
{
c.first()
}For Stack<i32>, the item type is obviously i32, yet peek carries an extra parameter. The next chapter shows how an associated type removes it.
Recap
- A trait lists required items, and may supply defaults.
- A bound or
whereclause tells the compiler what a generic type can do. - A generic trait parameter lets one type implement the trait many times.
- That flexibility becomes noise when the type is determined by the implementer.
Exercise
A type implements Container<i32> and also Container<String>. Is this allowed, and why?
Show answer
Yes. Container<i32> and Container<String> are different traits, so one type can implement both. The compiler then needs context to choose between them at each call.
Exercise
Rewrite fn largest<T: PartialOrd>(items: &[T]) -> &T using a where clause.
Show answer
fn largest<T>(items: &[T]) -> &T where T: PartialOrd { ... }. The bound is identical. Only the position changes.