Why this fires¶
An operator is used on a generic type parameter that doesn't carry the corresponding trait bound. Without the bound the compiler can't guarantee the operation is valid for every possible type argument.
fn add_two<T>(a: T, b: T) -> T {
return a + b
// ^^^^^ error[TE821]: operator `+` requires bound `Add` on `T`
}Fix it¶
Add the missing bound in either the angle-bracket or where form:
// Angle-bracket form
fn add_two<T: Add>(a: T, b: T) -> T {
return a + b
}
// where form (useful when multiple bounds are needed)
fn add_two<T>(a: T, b: T) -> T where T: Add {
return a + b
}Operator → bound mapping¶
| Operator | Required bound |
|---|---|
+ |
Add |
- (binary) |
Sub |
* |
Mul |
/ |
Div |
% |
Mod |
==, != |
Eq |
<, >, <=, >= |
Ord |
Only binary operators are gated. Unary - on a generic parameter is not
checked yet (its Neg bound is recognised but unenforced).