Sub topic 9
Traits with generic parameters
This chapter assumes you know how to define and implement a trait, how trait bounds work, and what associated types are. A trait can take type parameters, just like a struct or function. That lets one type implement the same trait several times, once for each choice of parameter.
Declaring a generic trait
Put the parameter in angle brackets after the trait name.
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 sum_all<S: Convert<f64>>(items: &[S]) -> f64 {
items.iter().map(|i| i.convert()).sum()
}
fn main() {
let m = Meters(2.5);
let n: f64 = m.convert();
let s: String = m.convert();
println!("{n} {s}");
println!("{}", sum_all(&[Meters(1.0), Meters(2.0)]));
}Convert<f64> and Convert<String> are two different traits as far as the compiler is concerned. Meters implements both, and the expected type picks which convert runs. In a bound, you write the parameter too, as in S: Convert<f64>.
Resolving ambiguity
Without a type annotation, m.convert() does not compile, because the compiler cannot tell which implementation you mean. Name the trait and its parameter to resolve it:
let n = <Meters as Convert<f64>>::convert(&m);Default type parameters
A trait parameter can have a default. The standard library's Add is declared as trait Add<Rhs = Self>, so impl Add for T means impl Add<T> for T. Naming Rhs lets you add a different right-hand type:
use std::ops::Add;
#[derive(Debug, Clone, Copy)]
struct Meters(f64);
impl Add for Meters {
type Output = Meters;
fn add(self, other: Meters) -> Meters {
Meters(self.0 + other.0)
}
}
impl Add<f64> for Meters {
type Output = Meters;
fn add(self, other: f64) -> Meters {
Meters(self.0 + other)
}
}
fn main() {
println!("{:?}", Meters(1.0) + Meters(2.0));
println!("{:?}", Meters(1.0) + 0.5);
}Parameter or associated type?
The two tools answer different questions.
| Row | Generic parameter | Associated type |
|---|---|---|
| Implementations per type | Many, one per parameter value | Exactly one |
| Who chooses it | The caller or the inference | The implementor |
| Example | `From<T>`, `Add<Rhs>` | `Iterator::Item` |
Use a parameter when a type can sensibly relate to several others. String implements From<&str> and From<char>, for example. Use an associated type when there is one natural answer. A given iterator has only one item type, so Iterator uses an associated type, and callers never have to write Iterator<u32>.
Exercise
A trait Parse<T> has the method fn parse_to(&self) -> T. Text implements both Parse<i32> and Parse<bool>. Why does let x = text.parse_to(); fail to compile, and what are two ways to fix it?
Show answer
The compiler cannot infer T because two implementations match, so the call is ambiguous. Fix it by annotating the variable (let x: i32 = text.parse_to();) or by naming the trait fully (<Text as Parse<i32>>::parse_to(&text)).