Sub topic 11
Writing generic code over operator traits
This chapter assumes you can write generic functions with trait bounds and that you know the Add trait, its Output associated type, and how operators move their operands. You will use those pieces to write functions that work for i32, f64, and your own types.
Operators are just trait bounds
An expression like a + b compiles only if the type of a implements Add<TypeOfB>. In generic code, T is unknown, so the compiler has nothing to go on. This fails:
fn sum2<T>(a: T, b: T) -> T { a + b }
error[E0369]: cannot add `T` to `T`The fix is to say in the signature which operator traits T supports. The bound is the permission slip for the operator.
| You write in the body | Bound you need |
|---|---|
| `a + b` | `T: Add<T>`, and `Output = T` if you return a `T` |
| `a * b` | `T: Mul<T>` |
| `acc += x` | `T: AddAssign<T>` |
| `-a` | `T: Neg` |
| `a < b` | `T: PartialOrd` |
| `v[i]` | `V: Index<I>` |
| `&a + &b` | `for<'a> &'a T: Add<&'a T>` |
The basic pattern: Add and Mul with Output = T
Add has a default Rhs of Self, so T: Add means T: Add<T>. Writing Add<Output = T> pins the associated type, so the result of x + y is again a T. Without that, the result is an unknown <T as Add>::Output, and you could not feed it back into the next addition.
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:
Copylets the closure pattern(&x, &y)copy elements out of the slices. Operators take their operands by value, so withoutCopyyou would be trying to move out of a borrowed slice.Defaultsupplies a starting value. For every built-in number type,Default::default()is zero.Add<Output = T>andMul<Output = T>letacc + x * ytype-check asT.
Diagram: how the bounds feed the body
When Output is not T
The Output = T constraint is convenient but sometimes too strict. A Vec2 times an f64 gives a Vec2, and the two operands have different types. A generic function can name the result type through the trait:
use std::ops::Mul;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
impl Mul<f64> for Vec2 {
type Output = Vec2;
fn mul(self, k: f64) -> Vec2 {
Vec2 { x: self.x * k, y: self.y * k }
}
}
fn scale_all<T, K>(items: &[T], k: K) -> Vec<<T as Mul<K>>::Output>
where
T: Copy + Mul<K>,
K: Copy,
{
items.iter().map(|&x| x * k).collect()
}
fn main() {
let pts = [Vec2 { x: 1.0, y: 2.0 }, Vec2 { x: 3.0, y: 4.0 }];
let scaled = scale_all(&pts, 2.0_f64);
assert_eq!(scaled[1], Vec2 { x: 6.0, y: 8.0 });
assert_eq!(scale_all(&[1, 2, 3], 10), vec![10, 20, 30]);
}The return type Vec<<T as Mul<K>>::Output> reads as "whatever T * K produces". The function stays correct for any type, including ones where the product is a different type from the operands, such as a length times a length giving an area.
Here is a rule of thumb for choosing:
- Use
Output = Twhen the function accumulates or loops, because the result must be usable as the next input. - Use
<T as Op<K>>::Outputwhen the function only applies the operator once per element and returns the results.
Operators on references: higher-ranked bounds
Suppose T is not Copy, or copying is expensive. If the type has impls like &T + &T, you can use those, as in the reference impls chapter. The bound has to say that the impl exists for references of any lifetime:
use std::ops::Add;
fn sum_refs<T>(items: &[T]) -> T
where
T: Default,
for<'a> &'a T: Add<&'a T, Output = T>,
{
let mut acc = T::default();
for x in items {
acc = &acc + x;
}
acc
}
fn main() {
assert_eq!(sum_refs(&[1, 2, 3]), 6);
assert_eq!(sum_refs(&[0.5, 0.25]), 0.75);
}The for<'a> clause is a higher-ranked trait bound (HRTB). It means "for every lifetime 'a, &'a T implements Add<&'a T>". It is needed because &acc and x are borrows that exist only briefly inside the loop. A plain lifetime parameter on the function would force a single borrow to outlive the whole call, which &acc cannot do.
The assignment acc = &acc + x is accepted because Output = T has no lifetime. The borrow of acc ends as soon as add returns, so overwriting acc is fine.
Standard integers and floats implement Add for reference pairs, so this function works for them. Your own types only qualify if you wrote those impls.
Compound assignment avoids Output entirely
AddAssign mutates the left operand and returns nothing, so there is no Output to name. This makes the bound shorter, and it is a good choice for accumulators:
use std::ops::AddAssign;
fn accumulate<T>(items: &[T]) -> T
where
T: Copy + Default + AddAssign,
{
let mut acc = T::default();
for &x in items {
acc += x;
}
acc
}
fn main() {
assert_eq!(accumulate(&[1, 2, 3]), 6);
assert_eq!(accumulate(&[1.5, 2.5]), 4.0);
}This also shows a design point: a type can implement AddAssign without implementing Add, and the reverse. A generic function should ask only for the operators it actually uses.
Prefer a standard trait when one exists
For summing and multiplying a whole iterator, the standard library already has std::iter::Sum and std::iter::Product. They are the idiomatic bound for "can be totalled":
use std::iter::Sum;
fn total<T>(items: &[T]) -> T
where
T: Copy + Sum<T>,
{
items.iter().copied().sum()
}
fn main() {
assert_eq!(total(&[1, 2, 3]), 6);
assert_eq!(total(&[0.5, 0.5]), 1.0);
}Sum also removes the Default problem above, because the implementer defines what an empty sum is. For a user type, implement Sum yourself by folding with your Add. For wider numeric abstractions (zero, one, casts), the third-party num-traits crate provides Zero, One, and Num, which the standard library does not have.
Common errors and what they mean
cannot add T to T(E0369). The body uses an operator with no matching bound. AddT: Add<Output = T>or the right trait.mismatched types: expected T, found <T as Add>::Output. You wroteT: AddwithoutOutput = T, then returned or reused the result as aT.use of moved value. The operator consumed a non-Copyoperand. AddCopy, addCloneand call.clone(), or switch to reference operators with an HRTB.the trait bound ... Add<&T> is not satisfied. You wrote&a + &bbut bounded onlyT: Add. The reference impl is a separate impl and needs its own bound.- Literal inference trouble. Calls such as
scale_all(&pts, 2.0)can be ambiguous whenThas severalMulimpls. Annotate with2.0_f64.
Trade-offs
Each approach has a cost:
| Approach | Strength | Cost |
|---|---|---|
| `Copy + Add<Output = T>` | Simple signatures | Excludes `String`, big numbers, vectors |
| `Clone + Add<Output = T>` | Works for more types | Allocates on every `.clone()` |
| HRTB on `&T` | No copies, no moves | Harder to read, needs reference impls |
| `AddAssign` | No `Output`, in-place | Needs a starting value, mutable state |
| `Sum` / `Product` | Idiomatic for iterators | Only for whole-iterator folds |
Generic code is monomorphized, so each concrete T gets its own compiled copy. Calling dot::<i32> has the same runtime cost as writing the loop by hand.
Exercise
Write fn sum_squares<T>(items: &[T]) -> T that returns the sum of the squares of the items. Which bounds does it need if you use acc + x * x with a Default start value, and what happens if you remove Output = T from the Mul bound?
Show answer
Use T: Copy + Default + Add<Output = T> + Mul<Output = T>. A body such as items.iter().fold(T::default(), |acc, &x| acc + x * x) then compiles. Copy is needed to copy x out of the slice and to use it twice in x * x. If you write only Mul with no Output = T, then x * x has type <T as Mul>::Output, which the compiler cannot show to be T. The following acc + ... then fails with a type mismatch, because Add<T> expects a T on the right-hand side.