Sub topic 2
Your first overload: implementing Add
This chapter assumes you know Rust structs and impl blocks, how to implement a trait, basic generics, and the Copy trait. You should also know what an associated type is. We implement Add for a small vector type and look at what the compiler does with a + b.
The trait behind `+`
The + operator calls a method on the Add trait from std::ops. Its definition is:
pub trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}Rhs is the type of the right-hand operand. It defaults to Self, so impl Add for Vec2 means impl Add<Vec2> for Vec2. Output is the type of the result. Later chapters cover both in detail. Here we use the defaults.
Implementing Add for Vec2
Start with a struct for a 2D point or vector. The derive line gives us printing, copying, and equality for the tests.
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);
}The impl has three parts:
use std::ops::Add;brings the trait into scope. You need it to write theimpland to callAdd::addby name. The+operator itself works without the import.type Output = Vec2;says that adding twoVec2values produces aVec2.fn add(self, rhs: Vec2) -> Vec2does the work. Here it adds the matching fields.
What the compiler does
The expression a + b is sugar for Add::add(a, b). The last assertion in main shows that both forms give the same result. The compiler finds the Add impl from the type of the left operand and the type of the right operand. If no impl matches, you get an error such as "cannot add Vec2 to f64".
Why Copy matters here
add takes self and rhs by value. For a type that is not Copy, a + b moves both a and b, and you cannot use them afterward. Vec2 derives Copy, so the operands are copied and stay usable. That is why a + b and then Add::add(a, b) both compile in main above.
For non-Copy types, the fix is to implement Add for references. A later chapter covers that.
Common errors
| Symptom | Likely cause |
|---|---|
| `cannot add Vec2 to Vec2` | No `impl Add` exists, or it is for a different `Rhs`. |
| `use of moved value` after `a + b` | The type is not `Copy`, so the operator consumed it. |
| `mismatched types` in the body of `add` | `Output` and the returned value do not agree. |
| `not in scope` for `Add::add` | The `use std::ops::Add;` line is missing. |
Checking your work
Try changing Output to a different type, such as f64, and make add return the sum of all four fields. The code still compiles, because Output is independent of the operand types. This is legal but is usually a poor design, which the design guidelines chapter returns to.
Exercise
Given impl Add for Vec2 with type Output = Vec2, what trait call does a + b become, and what happens to a and b if Vec2 does not implement Copy?
Show answer
a + b becomes Add::add(a, b). Both operands are passed by value, so without Copy they are moved into the call and cannot be used again afterward.
Exercise
Write an impl Sub for Vec2 that subtracts field by field. Which use line do you need?
Show answer
Add use std::ops::Sub; and 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 } } }.