Sub topic 12
What you may implement: the orphan rule
This chapter assumes you can write impl Trait for Type blocks and have seen Add, Mul and the Rhs parameter in earlier chapters. It explains which operator impls the compiler accepts and which it rejects.
The rule in one sentence
Every operator is a trait in std::ops, so an operator impl is a trait impl. Rust only lets you write a trait impl if your crate "owns" part of it. This is the orphan rule. Without it, two unrelated crates could each implement Add for the same pair of foreign types, and the compiler could not pick one.
In practice, an impl is allowed when at least one of these is local to your crate:
- the trait itself, or
- the type the impl is for (
Self), or - a type argument of the trait, such as the
RhsinMul<Rhs>.
The operator traits all come from std, so the trait is never local. Your impl needs a local type somewhere in the list of types.
Applying it to operators
A stricter detail applies to generics. An uncovered type parameter, meaning a bare T that is not wrapped inside another type, may not appear before the first local type.
| Impl | Allowed | Reason |
|---|---|---|
| `impl Add for Vec2` | Yes | `Vec2` is local and is `Self`. |
| `impl Mul<Vec2> for f64` | Yes | `f64` is foreign but is a concrete type, and the local `Vec2` is a trait argument. |
| `impl Add for Vec<i32>` | No (E0117) | The trait, `Self` and the `Rhs` default are all foreign. |
| `impl<T> Mul<Vec2> for T` | No (E0210) | The uncovered `T` comes before the first local type. |
The second row is why 2.0 * v can work. The earlier Mul<Vec2> for f64 example is legal only because Vec2 is a local type argument.
The newtype workaround
You cannot add + to Vec<i32> directly. Wrap it in a tuple struct you own. This is the newtype pattern, and the wrapper is a local type, so the impl is legal.
use std::ops::Add;
#[derive(Debug, PartialEq)]
struct Ints(Vec<i32>);
impl Add for Ints {
type Output = Ints;
fn add(self, rhs: Ints) -> Ints {
Ints(self.0.iter().zip(&rhs.0).map(|(a, b)| a + b).collect())
}
}
fn main() {
let a = Ints(vec![1, 2]);
let b = Ints(vec![10, 20]);
assert_eq!(a + b, Ints(vec![11, 22]));
}The cost is that Ints does not inherit the methods of Vec<i32>. You either reach into .0 or forward the methods you need.
Common errors
- Implementing for a dependency's type. "Foreign" means foreign to your crate, not to the standard library. If a library crate defines
Point, your application cannot writeimpl Add for Point. Wrap it in a newtype, or add the impl in the library. - Blanket impls on operators.
impl<T: Display> Add<Vec2> for Tfails with E0210. Write the impl for each concrete type you need, and use a macro if there are many. - Assuming references are local.
&Vec2and&mut Vec2count as local whenVec2is local, soimpl Add<&Vec2> for &Vec2is fine.&Vec<i32>is not local. - Expecting coherence to be optional. You cannot opt out of the rule. If you need an impl the rule forbids, the newtype is the standard answer.
Exercise
A crate defines struct Meters(f64);. Which of these impls compile in that crate: (1) impl Add<Meters> for f64, (2) impl Add<f64> for Vec<f64>, (3) impl<T> Add<Meters> for T?
Show answer
Only (1) compiles. In (1), Meters is a local trait argument and f64 is a concrete type, so the rule is satisfied. In (2) every type is foreign (Add, Vec<f64>, f64), which gives E0117. In (3) the uncovered type parameter T appears before the first local type Meters, which gives E0210.
Exercise
You depend on a crate that exports Money with no Add impl. How can your application make + work on money values?
Show answer
Define a newtype such as struct MyMoney(Money); in your crate and implement Add for it. The wrapper is local, so the orphan rule allows the impl. You can also ask the owning crate to add the impl.