Sub topic 12
What you may implement: the orphan rule
This chapter assumes you can write impl Trait for Type blocks and use generic parameters and associated types. It also assumes you have read the earlier chapters on Add, Output and the Rhs parameter. Here you will learn which operator impls the compiler accepts, why it rejects the others, and how to work around each rejection.
Why the rule exists
Every operator impl is a trait impl, so the compiler's trait coherence rules apply to it. Coherence means that for any trait and any set of types, at most one impl applies, and that impl is found without ambiguity.
Suppose two crates could each write impl Add for f64. A program that depends on both would have two competing definitions of 1.0 + 2.0. Rust prevents this with the orphan rule. An impl is an orphan if neither the trait nor the types involved belong to your crate. You may only write impls that are tied to your own crate.
Operators are where most people meet this rule first. You write impl Mul<Vec2> for f64, and it compiles. You write impl Add for f64, and it does not.
The rule stated precisely
Take an impl of the form impl<P1..Pm> Trait<T1..Tn> for T0. Here T0 is the type the impl is for, and T1..Tn are the trait's type arguments, such as Rhs. The impl is allowed if at least one of these holds:
Traitis defined in your crate.- At least one of
T0..Tnis a local type, and no uncovered type parameter appears in the types before the first local type.
For operator traits, rule 1 never applies, because the traits live in std::ops. Rule 2 decides everything.
A local type is a struct, enum or union defined in your crate. A few std wrappers are marked #[fundamental], and they do not hide locality: &Local, &mut Local, Box<Local> and Pin<Local> all count as local. Other wrappers do not. Vec<Local>, Option<Local> and (Local, Local) are not local.
A type parameter is covered when it appears inside another type, as in Wrapper<T>. It is uncovered when it stands alone, as in a bare T.
The compiler checks the types in order, T0 first, then T1, and so on. Anything before the first local type must not be a bare type parameter. This ordering is why Mul<Vec2> for f64 works, even though f64 comes first.
Cases that compile
The next program shows three allowed impls. In each one, Vec2 is the local type, and it appears in a different position each time.
use std::ops::{Add, Mul};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
// Local type is the trait argument (T1). T0 = f64 is not a type parameter.
impl Mul<Vec2> for f64 {
type Output = Vec2;
fn mul(self, v: Vec2) -> Vec2 {
Vec2 { x: self * v.x, y: self * v.y }
}
}
// T0 is a foreign tuple. The local Vec2 in T1 is enough.
impl Add<Vec2> for (f64, f64) {
type Output = Vec2;
fn add(self, v: Vec2) -> Vec2 {
Vec2 { x: self.0 + v.x, y: self.1 + v.y }
}
}
// A reference to a local type is itself local.
impl Add<&Vec2> for &Vec2 {
type Output = Vec2;
fn add(self, rhs: &Vec2) -> Vec2 {
Vec2 { x: self.x + rhs.x, y: self.y + rhs.y }
}
}
fn main() {
let v = Vec2 { x: 1.0, y: 2.0 };
assert_eq!(2.0 * v, Vec2 { x: 2.0, y: 4.0 });
assert_eq!((10.0, 20.0) + v, Vec2 { x: 11.0, y: 22.0 });
assert_eq!(&v + &v, Vec2 { x: 2.0, y: 4.0 });
}The second impl surprises many people. The Self type, (f64, f64), is entirely foreign. It is allowed because Vec2 appears as Rhs and nothing before it is a bare type parameter.
Cases that do not compile
Foreign trait, foreign types
impl Add for f64 { /* ... */ } // E0117
impl Add<f64> for Vec<f64> { /* ... */ } // E0117Both Add and every type involved belong to std. You have no claim on this impl, and std has already provided its own where it makes sense.
Wrapping a local type in a non-fundamental container
impl Add for Vec<Vec2> { /* ... */ } // E0117Vec<Vec2> is not local, even though it contains a local type. Vec is not #[fundamental]. Only &, &mut, Box and Pin pass locality through.
A bare type parameter before the local type
impl<T> Mul<Vec2> for T { /* ... */ } // E0210
impl<T: Into<f64>> Mul<Vec2> for T { /* ... */ } // E0210Here T0 is a bare T, and the local Vec2 only shows up afterwards. This is the case that most often catches people. The reason is a future-compatibility one. The std crate could later add impl Mul<Vec2> for SomeNewType, but it cannot know about your Vec2. Because T could be any type, including types that std or another crate might add, your blanket impl could overlap with theirs. The compiler refuses it now to prevent that.
The reverse is fine. impl<T> Mul<T> for Vec2 has the local type in T0, so the bare T after it is allowed. Whether it overlaps with your own other impls is a separate question, and the compiler checks that independently.
Quick reference
| Impl | Allowed | Reason |
|---|---|---|
| `impl Mul<Vec2> for f64` | Yes | `Vec2` is local, nothing before it is a type parameter |
| `impl Add<Vec2> for (f64, f64)` | Yes | Same reason |
| `impl Add<Vec2> for &Vec2` | Yes | `&Local` is local |
| `impl Neg for Box<Vec2>` | Yes | `Box<Local>` is local |
| `impl<T> Mul<T> for Vec2` | Yes | `T0` is local |
| `impl<T> Mul<Wrapper<T>> for f64` | Yes | `T` is covered by the local `Wrapper` |
| `impl Add for f64` | No | Nothing local |
| `impl Add for Vec<Vec2>` | No | `Vec` is not fundamental |
| `impl<T> Mul<Vec2> for T` | No | Uncovered `T` precedes the local type |
Working around the rule
Use a newtype
When you want operators on a foreign type, wrap it in a newtype. A newtype is a tuple struct with one field that you define yourself. The wrapper is local, so every impl on it is yours to write.
use std::ops::Add;
#[derive(Debug, Clone, PartialEq)]
struct Samples(Vec<f64>);
impl From<Vec<f64>> for Samples {
fn from(v: Vec<f64>) -> Self {
Samples(v)
}
}
impl Add for Samples {
type Output = Samples;
fn add(self, rhs: Samples) -> Samples {
Samples(self.0.iter().zip(&rhs.0).map(|(a, b)| a + b).collect())
}
}
fn main() {
let a = Samples::from(vec![1.0, 2.0]);
let b = Samples::from(vec![10.0, 20.0]);
assert_eq!(a + b, Samples(vec![11.0, 22.0]));
}The cost is that the wrapper does not inherit the inner type's methods. You must forward the ones you need, or expose the inner value through a field or accessor.
Write one impl per scalar type
You cannot write a single impl<T: Into<f64>> Mul<Vec2> for T. To let f32, f64 and i32 all scale a Vec2 from the left, write a separate impl for each concrete type. That is repetitive, so the chapter on macro_rules shows how to generate those impls from a list.
Move the generic parameter
If you control the right-hand type, put the generic parameter there. Use impl<T> Mul<Wrapper<T>> for f64, with T covered by Wrapper. Do not write impl<T> Mul<Wrapper> for T.
Consequences for library authors
The rule also applies in the other direction. If you publish a crate with an operator impl, you commit to it. For example, if you write impl Mul<MyType> for f64 and later remove it, downstream crates that used 2.0 * x stop compiling.
Adding a blanket impl to a published crate, such as impl<T: Display> Add<MyType> for T, can also break callers. A downstream crate may already have its own impl that now overlaps with yours. The orphan rule limits who can write impls. It does not stop impls from overlapping, so check your own impls for overlap as well.
Summary of the working model
- Operator traits come from
std::ops, so the trait is never local. A local type must appear somewhere inSelfor the trait arguments. &Local,&mut LocalandBox<Local>count as local.Vec<Local>andOption<Local>do not.- A bare type parameter may not appear before the first local type.
- Newtypes and per-type impls are the standard ways around a rejection.
Exercise
Which of these impls does the compiler accept, given that Money is a struct defined in your crate? Explain each answer using the orphan rule. (a) impl Add<Money> for u32 (b) impl Add for Option<Money> (c) impl<T> Add<Money> for T (d) impl<T> Add<T> for Money (e) impl Sub<Money> for &Money
Show answer
(a) Accepted. Money is a local type in the Rhs position, and u32 is not a type parameter, so nothing uncovered comes before it. (b) Rejected with E0117. Option is not #[fundamental], so Option<Money> is not local, and Add is a foreign trait. (c) Rejected with E0210. The bare T appears in Self before the first local type. (d) Accepted by the orphan rule, because Money is T0 and is local. It might still conflict with other Add impls for Money, which is a separate overlap check. (e) Accepted. &Money is local because references are fundamental.