Sub topic 2
Your first overload: implementing Add
What this chapter assumes
This chapter assumes you know Rust structs and impl blocks, how to implement a trait, basic generics and trait bounds, ownership and the Copy trait, and associated types. The previous chapter showed that a + b is sugar for a trait method call. Here you write that trait implementation yourself and see what the compiler requires.
The shape of the Add trait
The + operator is backed by the Add trait in std::ops. Its definition is:
pub trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}Four details matter here.
Rhsis a type parameter for the right-hand operand. It defaults toSelf, soimpl Add for Tmeansimpl Add<T> for T.Outputis an associated type. It names the type of the result, and it does not have to beSelf.addtakesselfby value, not by reference. The left operand is moved into the call.rhsis also taken by value.
You implement the trait on the type of the left operand. For a + b, the compiler looks for an Add<B> implementation on the type of a.
A complete example
The following program defines a two-dimensional vector and implements Add for it.
use std::ops::Add;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
impl Add 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 a = Vec2 { x: 1.0, y: 2.0 };
let b = Vec2 { x: 3.0, y: 4.0 };
assert_eq!(a + b, Vec2 { x: 4.0, y: 6.0 });
assert_eq!(Add::add(a, b), a + b);
}Walk through the pieces:
use std::ops::Add;brings the trait into scope. You need it to write theimplby its short name. You also need it to callAdd::addexplicitly, asmaindoes.impl Add for Vec2uses the defaultRhs = Self, so both operands areVec2.type Output = Vec2;declares that adding two vectors yields a vector.fn add(self, rhs: Vec2) -> Vec2builds the result field by field. Inside the body,self.x + rhs.xis itself anf64addition, which is a built-in operation and not a trait call you wrote.
The last assertion shows the equivalence directly. a + b and Add::add(a, b) produce the same value.
Why derive Copy matters here
Vec2 derives Clone and Copy. Because add takes self and rhs by value, a non-Copy type is moved into the call. After a + b, you could not use a or b again.
With Copy, the operands are copied, so the final line of main can use a and b after they have already appeared in a + b. Without Copy, the second use would fail with a "use of moved value" error. Later chapters cover what to do for types that cannot be Copy, such as implementing the operator on references.
Output is not always Self
Output can be any type. The compiler does not require that adding two things gives the same kind of thing. The standard library has real examples of this. Subtracting two Instant values gives a Duration, and adding a Duration to an Instant gives an Instant.
Here is a small example of an operator whose result differs from its operands. Subtracting two points gives a displacement.
use std::ops::Sub;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: f64,
y: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Displacement {
dx: f64,
dy: f64,
}
impl Sub for Point {
type Output = Displacement;
fn sub(self, rhs: Point) -> Displacement {
Displacement { dx: self.x - rhs.x, dy: self.y - rhs.y }
}
}
fn main() {
let start = Point { x: 1.0, y: 1.0 };
let end = Point { x: 4.0, y: 5.0 };
assert_eq!(end - start, Displacement { dx: 3.0, dy: 4.0 });
}The next chapter covers Output in more detail. For now, remember that Output is part of the contract. The result type of a + b is <A as Add<B>>::Output.
Making the operator work for different shapes of impl
Generic structs
If your type has a type parameter, the impl needs bounds on that parameter. This Pair adds element-wise when its element type can be added.
use std::ops::Add;
#[derive(Debug, PartialEq)]
struct Pair<T> {
a: T,
b: T,
}
impl<T: Add<Output = T>> Add for Pair<T> {
type Output = Pair<T>;
fn add(self, rhs: Pair<T>) -> Pair<T> {
Pair { a: self.a + rhs.a, b: self.b + rhs.b }
}
}
fn main() {
let p = Pair { a: 1, b: 2 } + Pair { a: 10, b: 20 };
assert_eq!(p, Pair { a: 11, b: 22 });
let q = Pair { a: 0.5, b: 1.5 } + Pair { a: 0.5, b: 0.5 };
assert_eq!(q, Pair { a: 1.0, b: 2.0 });
}The bound T: Add<Output = T> says two things. T must be addable to itself, and the result of that addition must be T again. Without the Output = T part, self.a + rhs.a would have type <T as Add>::Output, which the compiler cannot assume is T, so constructing Pair<T> would fail to type check.
Pair<T> is not Copy here. That is fine because the fields are moved into the addition. Each T value is consumed by +. For i32 and f64 that is a copy, so it works.
Common errors
Missing import
If you write impl Add for Vec2 without use std::ops::Add;, the compiler reports that Add cannot be found in this scope. Either import it or write impl std::ops::Add for Vec2.
Wrong Output
If the body returns a type different from the declared Output, you get a normal mismatched types error pointing at the return expression. If you change Output, update the return type of add to match. Writing -> Self::Output in the signature avoids repeating it.
Using a moved value
This code fails to compile:
use std::ops::Add;
#[derive(Debug)]
struct Money(u32);
impl Add for Money {
type Output = Money;
fn add(self, rhs: Money) -> Money {
Money(self.0 + rhs.0)
}
}
fn main() {
let a = Money(5);
let b = Money(7);
let total = a + b;
println!("{:?} {:?}", total, a);
}The error says a was moved by the + operation. Either derive Copy and Clone on Money, clone before adding, or implement Add for &Money. The last option is covered in a later chapter.
Adding a type that has no impl
Vec2 { .. } + 1.0 fails with "cannot add {float} to Vec2". The compiler found Add<Vec2> for Vec2 but no Add<f64> for Vec2. Mixed operand types need their own impls, which a later chapter covers.
Operand order
The impl is on the left operand's type. impl Add<f64> for Vec2 makes v + 2.0 valid but does not make 2.0 + v valid. That second form needs a separate impl on f64.
Implementing add without repeating field logic
When the type is a thin wrapper, you can delegate to the inner type. This keeps the impl short and hard to get wrong.
use std::ops::Add;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Meters(f64);
impl Add for Meters {
type Output = Meters;
fn add(self, rhs: Meters) -> Meters {
Meters(self.0 + rhs.0)
}
}
fn main() {
let total = Meters(1.5) + Meters(2.5);
assert_eq!(total, Meters(4.0));
}A newtype like this is a common first use of Add. It also gives you type safety. Meters(1.0) + Feet(3.0) does not compile unless you write an impl for that pair on purpose.
Summary of rules
| Question | Answer |
|---|---|
| Which type gets the impl? | The type of the left operand. |
| What does `impl Add for T` mean? | `impl Add<T> for T`, since `Rhs` defaults to `Self`. |
| How are operands passed? | By value, so non-`Copy` types are moved. |
| What is the result type? | The associated type `Output`, which you choose. |
| Is `a + b` the same as `Add::add(a, b)`? | Yes. The operator is sugar for the call. |
Exercise
Given #[derive(Debug, Clone, Copy, PartialEq)] struct Vec2 { x: f64, y: f64 } with impl Add for Vec2, write the impl Sub for Vec2 so that a - b gives the component-wise difference. What do you need to import, and what is Output?
Show answer
Import std::ops::Sub. Then write impl Sub for Vec2 { type Output = Vec2; fn sub(self, rhs: Vec2) -> Vec2 { Vec2 { x: self.x - rhs.x, y: self.y - rhs.y } } }. Output is Vec2 because subtracting two vectors gives a vector. The default Rhs = Self applies, so rhs is also a Vec2.
Exercise
Why does let t = a + b; println!("{:?}", a); fail for a struct that implements Add but does not derive Copy, and name two ways to fix it.
Show answer
Add::add takes self by value, so a is moved into the call and cannot be used afterwards. Fix it by deriving Clone and Copy so the operands are copied, or by calling a.clone() + b to keep the original. Implementing Add for &T is a third option.