Sub topic 11
Writing generic code over operator traits
This chapter assumes you know generics and trait bounds, associated types, and the Copy trait. You should also have seen how Add and Mul are implemented for a user type.
Operators as bounds
An operator trait is a normal trait, so you can use it as a bound. If a function needs + on values of type T, ask for T: Add. The Output associated type tells the compiler what a + b produces. Without more information, that type might not be T.
Writing Add<Output = T> fixes the output to T. Then the result of a + b can be added again or returned as T.
use std::ops::{Add, Mul};
fn dot<T>(a: &[T], b: &[T]) -> T
where
T: Copy + Default + Add<Output = T> + Mul<Output = T>,
{
a.iter()
.zip(b)
.fold(T::default(), |acc, (&x, &y)| acc + x * y)
}
fn main() {
assert_eq!(dot(&[1, 2, 3], &[4, 5, 6]), 32);
assert_eq!(dot(&[0.5, 2.0], &[2.0, 1.5]), 4.0);
}Each bound has a job:
| Bound | Why it is needed |
|---|---|
| `Copy` | `x` and `y` are used by value, so the values must be copyable out of the slices. |
| `Default` | `T::default()` gives the starting value of the sum. For numbers it is zero. |
| `Add<Output = T>` | `acc + ...` must produce a `T` to feed back into the fold. |
| `Mul<Output = T>` | `x * y` must produce a `T` that can be added. |
The same function works for i32, f64, and any type of yours that implements these traits. Your Vec2 would not work here, because it does not implement Default.
How the compiler checks the body
Rust checks a generic function once, against its bounds, not once per type. Inside dot, the only operations allowed on T are the ones the bounds promise. If you remove Mul<Output = T>, the expression x * y fails to compile, even if every caller would have used i32.
Common errors
- Forgetting
Output = T. With a bareT: Add, the result ofa + bhas type<T as Add>::Output. Returning it asTgives a type mismatch error. - Forgetting
Copy. Operators take operands by value. WithoutCopy, usingxtwice moves it the first time, and the compiler reports a use of a moved value. - Using references with by-value bounds.
T: Add<Output = T>coversT + T, not&T + &T. A type such asSeriesthat implements only the reference form needs a different bound, shown below.
Bounding references
To accept types that are cheap to add by reference but costly to copy, use a higher-ranked bound. It says the bound holds for a reference of any lifetime.
use std::ops::Add;
fn sum_pair<T>(a: &T, b: &T) -> T
where
for<'a> &'a T: Add<&'a T, Output = T>,
{
a + b
}
fn main() {
assert_eq!(sum_pair(&2, &3), 5);
assert_eq!(sum_pair(&1.5, &2.0), 3.5);
}Standard numeric types implement Add for references, so both calls compile. Use this form when your type is expensive to clone, like the Series type from the reference impls chapter.
Exercise
A generic function fn double<T: Add<Output = T>>(x: T) -> T { x + x } fails to compile with a "use of moved value" error. Which bound fixes it, and why?
Show answer
Add the bound Copy (so T: Copy + Add<Output = T>). The + operator takes both operands by value, and x + x uses x twice. Without Copy, the first use moves x, so the second use is invalid.
Exercise
Why does dot not compile for the Vec2 type from earlier chapters, even if Vec2 implements Add and Mul<f64>?
Show answer
dot requires Mul<Output = T>, which means Mul<T> for T, so Vec2 * Vec2 must exist. Vec2 implements Mul<f64>, not Mul<Vec2>. It also lacks Default, which dot needs for the starting value.