Sub topic 1
How operators map to std::ops traits
In Rust, an operator such as + or [] is shorthand for a method call on a trait. The compiler rewrites a + b into a call to a trait method and then checks the types as it would for any other call. This chapter shows the mapping, where the traits live, and which operators you can't overload. The rest of the tutorial builds on this model.
Prerequisites
This chapter assumes you already know:
- How to define structs and write
implblocks. - How to implement a trait for a type.
- Generics and trait bounds, such as
T: Copy. - Ownership, moves, borrowing, and the
Copytrait. - Associated types, such as
type Output = ...inside animpl.
If associated types are unfamiliar, read about them first. Every operator trait uses one.
Operators are method calls
Take the expression a + b. The compiler treats it as a call to the add method of the std::ops::Add trait. The two forms below mean the same thing:
use std::ops::Add;
fn main() {
let x = 2_i32;
let y = 3_i32;
assert_eq!(x + y, Add::add(x, y));
assert_eq!(x + y, x.add(y));
}The method form x.add(y) only compiles because Add is imported with use. The + operator needs no import, because the compiler refers to the trait directly.
The same holds for your own types. If a type implements Add, then + works on it. If it doesn't, + is a compile error:
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);
}Without the impl Add for Vec2 block, the line a + b fails with error E0369: the compiler reports that it cannot add Vec2 to Vec2. The message points at the missing trait implementation, not at the operator.
The shape of an operator trait
Binary operator traits all look alike. This is Add in the standard library, slightly simplified:
pub trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}Three parts matter:
Rhsis a type parameter for the right-hand operand. It defaults toSelf, soimpl Add for Vec2meansimpl Add<Vec2> for Vec2.Outputis an associated type. It is the type of the whole expression. It need not beSelforRhs.selfis taken by value. Both operands are moved into the call unless their types areCopy. Later chapters cover this in detail.
The trait is implemented for the left operand's type. In a + b, the compiler looks for impl Add<TypeOfB> for TypeOfA.
The operator table
Each operator belongs to one trait. Most live in std::ops. The comparison operators live in std::cmp.
| Operator | Trait | Method | Module | Column |
|---|---|---|---|---|
| `a + b` | `Add` | `add(self, rhs)` | `std::ops` | |
| `a - b` | `Sub` | `sub(self, rhs)` | `std::ops` | |
| `a * b` | `Mul` | `mul(self, rhs)` | `std::ops` | |
| `a / b` | `Div` | `div(self, rhs)` | `std::ops` | |
| `a % b` | `Rem` | `rem(self, rhs)` | `std::ops` | |
| `-a` | `Neg` | `neg(self)` | `std::ops` | |
| `!a` | `Not` | `not(self)` | `std::ops` | |
| `a & b`, `a \ | b`, `a ^ b` | `BitAnd`, `BitOr`, `BitXor` | `bitand`, `bitor`, `bitxor` | `std::ops` |
| `a << b`, `a >> b` | `Shl`, `Shr` | `shl`, `shr` | `std::ops` | |
| `a += b` and similar | `AddAssign` and similar | `add_assign(&mut self, rhs)` | `std::ops` | |
| `a[i]` | `Index`, `IndexMut` | `index`, `index_mut` | `std::ops` | |
| `a == b`, `a != b` | `PartialEq` | `eq`, `ne` | `std::cmp` | |
| `a < b`, `a <= b`, `a > b`, `a >= b` | `PartialOrd` | `partial_cmp`, `lt`, `le`, `gt`, `ge` | `std::cmp` |
The compound assignment family covers +=, -=, *=, /=, %=, &=, |=, ^=, <<= and >>=. Each has a trait named like SubAssign or ShlAssign.
Some other syntax is also backed by traits, including *x through Deref and x(...) through the Fn family. This tutorial does not cover them.
Not every symbol can be overloaded
Some operators have no trait, so their meaning is fixed:
&&and||short-circuit. The right side may never run, which a method call could not express.=is assignment. It always moves or copies the value.&and&mutas prefix operators create references. They are not the bitwise&.ascasts,?, and range syntax like..are built into the language or defined by other mechanisms.
Also, you can't invent new operators. You can only attach your types to the ones that exist.
Arithmetic moves, comparison borrows
Arithmetic operators call methods that take self by value. Comparison operators behave differently. a == b becomes PartialEq::eq(&a, &b), so the compiler borrows both operands for you.
fn main() {
let a = String::from("hi");
let b = String::from("hi");
// Comparison borrows: a and b are still usable afterwards.
assert!(a == b);
assert!(PartialEq::eq(&a, &b));
println!("{a} {b}");
// Addition moves the left operand.
let s = String::from("foo");
let t = s + "bar"; // String implements Add<&str>
// println!("{s}"); // error[E0382]: borrow of moved value: `s`
assert_eq!(t, "foobar");
}The String + &str case is a good model of the whole mechanism. The standard library implements Add<&str> for String. The left operand is moved in, the buffer is reused, and the result is a String. The Output type differs from the right operand's type, and that is allowed.
Compound assignment sits in between. a += b calls AddAssign::add_assign(&mut a, b). The left side is borrowed mutably, and the right side is still passed by value.
Primitive types use the same traits
Primitive types such as i32 and f64 implement these traits too, and the compiler also handles their operators directly. The traits matter in generic code. A function bounded by T: Add<Output = T> can accept i32, f64, or your own Vec2, because all of them implement Add:
use std::ops::Add;
fn sum_pair<T: Add<Output = T>>(a: T, b: T) -> T {
a + b
}
fn main() {
assert_eq!(sum_pair(1, 2), 3);
assert_eq!(sum_pair(1.5, 2.5), 4.0);
}Inside sum_pair, the compiler knows nothing about T except the bound. The bound is what makes a + b legal.
How the compiler resolves an operator
The compiler checks an operator expression in a fixed order. The diagram follows a + b.
Two consequences follow from this:
- Operand order matters.
impl Mul<f64> for Vec2gives youv * 2.0but not2.0 * v. The second form needs its own impl onf64, which a later chapter covers. - Type inference works with the impl. If several
Addimpls exist for a type, the type ofbselects one.
Common errors
The same few mistakes appear often when you start overloading operators:
- Missing impl. E0369 means no impl exists for that operand pair. Check both types, since
Vec2 * f64andf64 * Vec2are different impls. - Use after move. E0382 after an arithmetic expression means a non-
Copyoperand was moved. DeriveCopy, borrow the operands, or clone them. - Wrong
Outputassumption.a + bdoes not have to return the type ofa. Read theOutputof the impl you are calling. - Missing import for method form.
a.add(b)needsuse std::ops::Add. The+operator does not. - Wrong module for comparisons. Look for
PartialEqandPartialOrdinstd::cmp, notstd::ops.
Exercises
Exercise
The expression x - y appears in code where x and y have a user-defined, non-Copy type Money. Write the equivalent function-call form, name the trait it belongs to, and say what happens to x and y afterwards.
Show answer
It is Sub::sub(x, y), from std::ops::Sub. The method takes self and rhs by value, so both x and y are moved and cannot be used afterwards, because Money is not Copy.
Exercise
Which of these operators can you overload with a trait, and which trait or reason applies? &&, ==, +=, [], =.
Show answer
&& cannot be overloaded because it short-circuits and its right operand may never be evaluated. == uses PartialEq in std::cmp. += uses AddAssign in std::ops. [] uses Index and IndexMut in std::ops. = cannot be overloaded because assignment always moves or copies.