Sub topic 8
Associated types versus type parameters
This chapter assumes you can write a trait, implement it for a struct, and read a generic bound such as T: Display. A trait can mention other types in two ways: as an associated type declared inside the trait, or as a type parameter on the trait itself. The two look similar but answer different questions.
Associated types: one answer per implementing type
An associated type is a type placeholder that each implementation fills in once. The trait says "there is some Item", and the impl says which one.
use std::fmt::Debug;
trait Container {
type Item;
fn first(&self) -> Option<&Self::Item>;
}
struct Names(Vec<String>);
impl Container for Names {
type Item = String;
fn first(&self) -> Option<&String> {
self.0.first()
}
}
fn print_first<C: Container>(c: &C)
where
C::Item: Debug,
{
println!("{:?}", c.first());
}
fn main() {
let names = Names(vec![String::from("Ana"), String::from("Bo")]);
print_first(&names);
}Names can implement Container only once, so Names::Item is always String. The compiler can work out C::Item from C alone, and callers never write it. You can still constrain it, as in C::Item: Debug or Container<Item = String>.
Type parameters: many implementations per type
A trait with a type parameter can be implemented several times for the same type, once per argument.
trait Convert<T> {
fn convert(&self) -> T;
}
struct Celsius(f64);
impl Convert<f64> for Celsius {
fn convert(&self) -> f64 {
self.0 * 9.0 / 5.0 + 32.0
}
}
impl Convert<String> for Celsius {
fn convert(&self) -> String {
format!("{:.1}°C", self.0)
}
}
fn main() {
let c = Celsius(21.0);
let f: f64 = c.convert();
let s: String = c.convert();
println!("{f} {s}");
}Both implementations are legal because Convert<f64> and Convert<String> are different traits. The cost is that callers must supply enough context to pick one. Without the type annotations on f and s, the call c.convert() fails with "type annotations needed".
Choosing between them
Use these rules:
- If the extra type is determined by the implementing type, use an associated type.
Iterator::Itemis the standard example: a given iterator yields one kind of item. - If a type can meaningfully relate to many others, use a type parameter.
From<T>is the standard example:StringimplementsFrom<&str>,From<char>, and others. - Associated types make bounds shorter.
fn f<I: Iterator<Item = u32>>is simpler than a trait with a parameter, where every generic function must also name that parameter.
Common errors
- Writing
impl Container for Namestwice with differentItemtypes. This is error E0119, conflicting implementations. - Using a bare
Iteminside a generic function. WriteC::Itemor<C as Container>::Item. - Choosing a type parameter and then hitting "type annotations needed" at every call site. This usually means an associated type was the better fit.
Exercise
You are designing a trait Parse where each implementing type produces exactly one kind of error when parsing fails. Should the error type be an associated type or a type parameter? What would change if one type needed to be parsed from many different input formats?
Show answer
Use an associated type (type Error;), because each implementing type has one error type, which is how FromStr works. If one type had to be parsed from many input formats, a type parameter such as Parse<Input> would fit better, since a single type could then have one implementation per input type.