Sub topic 1
How Operators Map to `std::ops` Traits
Prerequisites
This chapter assumes you know Rust structs, impl blocks, traits, generics, associated types, ownership, borrowing, and Copy.
Operators Are Trait Calls
Rust operators are syntax for trait method calls. For example, a + b calls Add::add(a, b). The operator is convenient, but the trait defines its behavior for each type.
| Expression | Trait method |
|---|---|
| `a + b` | `Add::add(a, b)` |
| `a - b` | `Sub::sub(a, b)` |
| `a * b` | `Mul::mul(a, b)` |
| `-a` | `Neg::neg(a)` |
The traits are in the std::ops module. You implement the appropriate trait for your own type.
Your First Overload: Implementing `Add`
Here, Vec2 adds its coordinates independently:
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 });
}Add has a right-hand-side type parameter named Rhs. Its default is Self, so impl Add for Vec2 means Vec2 + Vec2. The add method receives both operands and returns the associated Output type.
Choosing `Output`
Output does not have to equal the left or right operand type. For example, adding a Duration and a rate might produce a different measurement type. Choose an output that describes the mathematical or domain result clearly.
> callout note > Operator behavior should match what readers naturally expect. If + performs validation, logging, or an unrelated action, use a named method instead.
Operands Are Moved
The basic Add implementation takes operands by value. For a non-Copy type, a + b moves both values, so they cannot be used afterward. Vec2 derives Copy, allowing small values to be copied implicitly. For larger types, borrow operands or implement operator traits for references in a later design.
Exercise
What trait method does left + right call, and what happens to non-Copy operands in a by-value Add implementation?
Show answer
It calls Add::add(left, right), and the operands are moved unless the type is Copy.