Sub topic 5
Associated type or generic parameter?
This chapter assumes you can write a trait, use generic bounds like T: Trait, and have seen Iterator with for loops. Here you will learn how to choose between two ways of letting a trait mention another type.
Two ways to add a type to a trait
A trait can take a type from outside, as a generic parameter: trait Convert<T>. It can also let each implementer pick the type, as an associated type: trait Parser { type Output; }.
The two look similar, but they differ in how many implementations a single type can have.
Generic parameter: many implementations per type
With a generic parameter, one type can implement the trait several times, once for each argument.
trait Convert<T> {
fn convert(&self) -> T;
}
struct Meters(f64);
impl Convert<f64> for Meters {
fn convert(&self) -> f64 {
self.0
}
}
impl Convert<String> for Meters {
fn convert(&self) -> String {
format!("{} m", self.0)
}
}
fn main() {
let m = Meters(2.5);
let a: f64 = m.convert();
let b: String = m.convert();
println!("{} {}", a, b);
}Convert<f64> and Convert<String> are different traits as far as the compiler is concerned. The caller must say which one it wants, here through the type annotations on a and b. Without them, the call m.convert() is ambiguous and fails to compile.
Associated type: one implementation per type
With an associated type, a type implements the trait at most once, so the associated type is fixed by the implementing type.
trait Parser {
type Output;
fn parse(&self, input: &str) -> Option<Self::Output>;
}
struct IntParser;
impl Parser for IntParser {
type Output = i32;
fn parse(&self, input: &str) -> Option<i32> {
input.trim().parse().ok()
}
}
fn run<P: Parser>(parser: &P, input: &str) -> Option<P::Output> {
parser.parse(input)
}
fn main() {
println!("{:?}", run(&IntParser, " 42 "));
}Once the compiler knows P is IntParser, it knows P::Output is i32. Nobody has to pass the output type along.
The cost of the generic version
Suppose Parser took a parameter, as in Parser<O>. Then run would need two type parameters, fn run<P: Parser<O>, O>(...). Every function that touches a parser would also have to name O. Worse, IntParser could implement Parser<i32> and Parser<String>, so inference often has too little information to choose.
How to decide
| Question | Generic parameter | Associated type |
|---|---|---|
| Implementations per type | Many, one per argument | One |
| Who picks the type | The caller, at each use | The implementer, once |
| Bound syntax | `T: Convert<f64>` | `T: Parser<Output = i32>` |
| Extra type parameters on generic functions | Often needed | Usually not |
Standard library examples show the pattern:
Iteratoruses an associatedItem. A given iterator yields one kind of item.From<T>uses a generic parameter. A type such asStringcan be built from&str,char, and more.Add<Rhs>uses both. The right-hand side is a parameter, because a type can be added to several types. The result,Output, is an associated type, because it is determined onceSelfandRhsare known.
Common mistakes
- Using a generic parameter when only one answer exists. This forces extra type parameters onto every generic function that uses the trait.
- Using an associated type when you need several implementations. The compiler reports conflicting implementations if you try to implement the trait twice for one type.
- Forgetting that a bound can fix an associated type. Writing
P: Parser<Output = i32>limits a function to parsers that producei32, without adding a type parameter.
Exercise
You are designing a trait Storage for a type that holds records. Each storage type (for example, FileStorage) stores exactly one kind of key. Should the key type be an associated type or a generic parameter on the trait? Now suppose instead a type Celsius must convert into f64, i32, and String through one trait. Which choice fits that case?
Show answer
For Storage, use an associated type (type Key;), because each storage type has a single key type and generic functions then need no extra parameter. For Celsius, use a generic parameter (trait Convert<T>), because the type needs several implementations of the same trait, one per target type.