Sub topic 9
Traits with generic parameters
This chapter assumes you can define and implement a trait, write a generic function with a trait bound, and read impl blocks. Earlier chapters covered all three.
A trait that takes a type parameter
A trait can declare type parameters, just as a struct or function can. The result is a family of traits. ConvertTo<f64> and ConvertTo<String> are different traits, and one type can implement both.
struct Meters(f64);
trait ConvertTo<T> {
fn convert(&self) -> T;
}
impl ConvertTo<f64> for Meters {
fn convert(&self) -> f64 {
self.0
}
}
impl ConvertTo<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();
let c = <Meters as ConvertTo<String>>::convert(&m);
println!("{a} | {b} | {c}");
}This prints 2.5 | 2.5 m | 2.5 m.
Each impl is a separate implementation, and the compiler must be able to tell which one a call uses. In main, the type annotations on a and b select the implementation. The last call uses fully qualified syntax, <Type as Trait<Param>>::method, to name the implementation explicitly.
Default type parameters
A trait parameter can have a default. The standard library's Add and Mul use this:
pub trait Mul<Rhs = Self> {
type Output;
fn mul(self, rhs: Rhs) -> Self::Output;
}Writing impl Mul for Vec2 means impl Mul<Vec2> for Vec2. You only write the parameter when the right-hand side differs from the implementing type. This lets one type support several kinds of multiplication.
use std::ops::Mul;
#[derive(Debug, Clone, Copy)]
struct Vec2 {
x: f64,
y: f64,
}
// Vec2 * f64 -> scaled vector
impl Mul<f64> for Vec2 {
type Output = Vec2;
fn mul(self, k: f64) -> Vec2 {
Vec2 { x: self.x * k, y: self.y * k }
}
}
// f64 * Vec2 -> scaled vector
impl Mul<Vec2> for f64 {
type Output = Vec2;
fn mul(self, v: Vec2) -> Vec2 {
v * self
}
}
// Vec2 * Vec2 -> dot product (Rhs defaults to Self)
impl Mul for Vec2 {
type Output = f64;
fn mul(self, other: Vec2) -> f64 {
self.x * other.x + self.y * other.y
}
}
fn main() {
let a = Vec2 { x: 1.0, y: 2.0 };
println!("{:?}", a * 2.0_f64);
println!("{:?}", 2.0_f64 * a);
println!("{}", a * a);
}Three results come from three implementations. The Output type changes with Rhs, so a single Mul implementation could not cover all three.
The second implementation, impl Mul<Vec2> for f64, is legal even though f64 and Mul both come from std. The orphan rule is satisfied because Vec2, a local type, appears as a trait parameter. The rule is covered in its own chapter.
Bounds on generic traits
You can use a generic trait in a bound by supplying its parameter:
fn sum_as_f64<T>(items: &[T]) -> f64
where
T: Copy + Into<f64>,
{
items.iter().map(|&i| Into::<f64>::into(i)).sum::<f64>()
}
fn main() {
println!("{:.1}", sum_as_f64(&[1_i32, 2, 3]));
println!("{:.1}", sum_as_f64(&[1.5_f32, 2.5]));
}T: Into<f64> means "T can be converted into f64". It accepts i32, f32, u8, and any other type with that implementation.
Bounds can also constrain the other side of the relationship. where i64: From<T> puts the bound on i64 instead of on T. where clauses allow this and inline bounds like <T: ...> do not. Associated types of a bound can be pinned with Add<Output = T>:
use std::ops::Add;
fn add_twice<T: Add<Output = T> + Copy>(a: T) -> T {
a + a
}Generic traits and trait objects
A trait object needs all its parameters filled in. dyn Handler<Click> is a valid type. dyn Handler on its own is not, because the parameter has no default.
struct Click {
x: i32,
}
trait Handler<E> {
fn handle(&self, event: &E) -> String;
}
struct Logger;
impl Handler<Click> for Logger {
fn handle(&self, event: &Click) -> String {
format!("click at x={}", event.x)
}
}
impl Handler<String> for Logger {
fn handle(&self, event: &String) -> String {
format!("message: {event}")
}
}
fn main() {
let handlers: Vec<Box<dyn Handler<Click>>> = vec![Box::new(Logger)];
for h in &handlers {
println!("{}", h.handle(&Click { x: 7 }));
}
println!("{}", Logger.handle(&String::from("hi")));
}Logger implements two instances of Handler. In the Vec, Box<dyn Handler<Click>> selects the Click instance, so the list holds only handlers for Click events. Calling Logger.handle(...) on a String selects the other instance through the argument type.
Type parameter or associated type
The previous chapter introduced associated types. The two features differ in how many implementations a type may have.
| Row | Type parameter (`Trait<T>`) | Associated type (`type Item;`) |
|---|---|---|
| Implementations per type | Many, one for each `T` | Exactly one |
| Who picks the type | The caller, by annotation or inference | The implementor |
| Callers must name it | Often, when inference cannot decide | Rarely |
| Examples | `From<T>`, `Into<T>`, `Mul<Rhs>`, `PartialEq<Rhs>` | `Iterator::Item`, `Deref::Target`, `Mul::Output` |
A good test is to ask whether a type could sensibly implement the trait more than once. A String can be built From<&str>, From<char>, and From<Box<str>>, so From takes a parameter. A Vec<u8> iterator has one item type, so Iterator uses an associated type.
Mul uses both. Rhs is a parameter because the right-hand side varies. Output is associated because, once Self and Rhs are fixed, the result type is determined.
Common errors
Inference failure is the most common problem. If a type has several implementations of a generic trait and nothing selects one, the compiler stops with an error:
let v = m.convert(); // error[E0283]: type annotations neededThere are three fixes. Annotate the binding (let v: f64 = ...), use the turbofish on the trait (ConvertTo::<f64>::convert(&m)), or use the fully qualified form shown earlier.
Two other mistakes show up often:
- Overlapping implementations.
impl<T> Handler<T> for Loggerandimpl Handler<Click> for Loggerconflict, because both apply toHandler<Click>. The compiler rejects overlap, as the coherence chapter explains. - Parameter on the wrong item. If a trait has one method that needs a type parameter, put the parameter on the method (
fn convert<T>(&self)), not on the trait. A trait-level parameter is for when the whole trait changes meaning with the type. A method-level parameter is for when a single implementation works for many types.
Exercise
Why is impl Iterator<u32> for Countdown not how the standard library defines Iterator, and which design question decides between a type parameter and an associated type?
Show answer
Iterator uses an associated type, Item, because a given iterator type yields exactly one kind of item, so there is only ever one implementation per type. The deciding question is whether a type can sensibly implement the trait more than once with different types. If it can (as with From<T>), use a type parameter. If there is only one answer (as with Iterator::Item), use an associated type.
Exercise
Given struct Celsius(f64); and trait ConvertTo<T> { fn convert(&self) -> T; }, write two implementations for Celsius, one to f64 (the raw value) and one to String (like "21.5 C"). Then write the call that selects the String one without a type annotation on a variable.
Show answer
impl ConvertTo<f64> for Celsius { fn convert(&self) -> f64 { self.0 } }
impl ConvertTo<String> for Celsius { fn convert(&self) -> String { format!("{} C", self.0) } }
The call is <Celsius as ConvertTo<String>>::convert(&c), or ConvertTo::<String>::convert(&c).