Sub topic 1
How operators map to std::ops traits
Prerequisites
This chapter assumes you can write Rust structs and impl blocks, and that you know how to implement a trait. You should also be comfortable with generics and trait bounds, with ownership and the Copy trait, and with associated types. Later chapters build on each of these.
Operators are method calls
In Rust, an operator on a user-defined type is a method call in disguise. The compiler rewrites a + b into a call to the add method of the Add trait. The traits live in the std::ops module. Each operator has one trait, and each trait has one method.
The two forms below are equivalent.
use std::ops::Add;
fn main() {
let x = 3_i32;
let y = 4_i32;
assert_eq!(x + y, Add::add(x, y));
assert_eq!(x + y, x.add(y));
}Primitive types such as i32 and f64 already implement these traits. Your own types get the same operators once you implement the matching trait. No special syntax is involved. You write an ordinary impl block.
The operator table
The table lists the most common operators, their traits, and their methods.
| Expression | Trait | Method |
|---|---|---|
| `a + b` | `Add` | `add(self, rhs)` |
| `a - b` | `Sub` | `sub(self, rhs)` |
| `a * b` | `Mul` | `mul(self, rhs)` |
| `a / b` | `Div` | `div(self, rhs)` |
| `a % b` | `Rem` | `rem(self, rhs)` |
| `-a` | `Neg` | `neg(self)` |
| `!a` | `Not` | `not(self)` |
| `a += b` | `AddAssign` | `add_assign(&mut self, rhs)` |
| `a[i]` | `Index` | `index(&self, i)` |
| `a[i] = v` | `IndexMut` | `index_mut(&mut self, i)` |
Bitwise and shift operators follow the same pattern. They are covered in a later chapter.
What the compiler checks
The rewrite happens during type checking. For a + b, the compiler looks for an implementation of Add<B> for the type of a, where B is the type of b. If it finds none, you get error E0369, "cannot add B to A". The fix is to implement the trait. It is not to change the expression.
Binary operator traits have a shape you will see repeatedly. They take the left operand as self and the right operand as a parameter. They also declare an associated type named Output for the result. Here is a simplified view of Add.
pub trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}Rhs is a type parameter that defaults to Self. Output is an associated type, so each implementation chooses its own result type. Later chapters explain both in detail.
A diagram of the lowering
Two things that are not overloadable
Some operators have no trait you can implement.
- The logical operators
&&and||cannot be overloaded. They short-circuit, which means the right side may never run, and a method call would always evaluate its arguments. - The assignment operator
=cannot be overloaded. It always moves or copies a value.
The comparison operators ==, !=, < and the rest are overloadable. They use PartialEq and PartialOrd from std::cmp, not std::ops.
Check your understanding
Exercise
The expression p - q fails to compile with E0369 for a struct Point. Which trait must you implement, and what is p - q rewritten to?
Show answer
Implement std::ops::Sub for Point. The expression is rewritten to Sub::sub(p, q), which is the same as p.sub(q).
Exercise
Why can && not be implemented through a trait the way + is?
Show answer
&& short-circuits, so the right operand must not be evaluated when the left is false. A trait method call evaluates all its arguments first, so the language keeps && built in.