Sub topic 12
Overloading operators with std::ops
This chapter assumes you can write a trait and an impl block, read generic bounds like T: Add<Output = T>, and know the difference between moving and borrowing a value. You will learn how Rust turns operators into trait calls, how to implement the common operator traits for your own types, and which mistakes to avoid.
Operators are trait method calls
Rust has no special operator-overloading feature. Each operator is shorthand for a method of a trait in std::ops. The expression p + q means Add::add(p, q). If the type of p has no Add implementation that accepts q, the compiler reports a missing trait implementation.
The most common operators and their traits:
| Operator | Trait | Method | Column |
|---|---|---|---|
| `+` | `Add` | `add` | |
| `-` | `Sub` | `sub` | |
| `*` | `Mul` | `mul` | |
| `/` | `Div` | `div` | |
| `%` | `Rem` | `rem` | |
| unary `-` | `Neg` | `neg` | |
| unary `!` | `Not` | `not` | |
| `+=`, `-=`, `*=` | `AddAssign`, `SubAssign`, `MulAssign` | `add_assign`, ... | |
| `a[i]` | `Index`, `IndexMut` | `index`, `index_mut` | |
| `&`, `\ | `, `^`, `<<`, `>>` | `BitAnd`, `BitOr`, `BitXor`, `Shl`, `Shr` | `bitand`, ... |
The comparison operators ==, <, and the rest belong to PartialEq and PartialOrd in std::cmp. Usually you get them with #[derive]. You cannot overload &&, ||, or =.
Implementing a binary operator
Add is declared roughly like this:
pub trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}Two details matter. Rhs is a generic parameter that defaults to Self, so impl Add for Point means impl Add<Point> for Point. Output is an associated type, so each implementation picks exactly one result type. This is the choice from the associated types chapter: the right-hand side can vary per impl, but the output is determined once the inputs are known.
Because Rhs is a parameter, one type can have several impls of the same operator trait. The program below also implements multiplication by a scalar, in both operand orders, plus negation and +=:
use std::ops::{Add, AddAssign, Mul, Neg};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point { x: self.x + other.x, y: self.y + other.y }
}
}
impl Mul<i32> for Point {
type Output = Point;
fn mul(self, k: i32) -> Point {
Point { x: self.x * k, y: self.y * k }
}
}
impl Mul<Point> for i32 {
type Output = Point;
fn mul(self, p: Point) -> Point {
p * self
}
}
impl Neg for Point {
type Output = Point;
fn neg(self) -> Point {
Point { x: -self.x, y: -self.y }
}
}
impl AddAssign for Point {
fn add_assign(&mut self, other: Point) {
self.x += other.x;
self.y += other.y;
}
}
fn main() {
let a = Point { x: 1, y: 2 };
let b = Point { x: 3, y: 4 };
let mut c = a + b * 2;
c += a;
println!("{:?}", c);
println!("{:?}", 3_i32 * a);
println!("{:?}", -b);
}This prints Point { x: 8, y: 12 }, Point { x: 3, y: 6 }, and Point { x: -3, y: -4 }.
The impl Mul<Point> for i32 block is allowed even though i32 is a foreign type. The orphan rule only requires that the impl involve a local type, and Point appears as the trait's type parameter. Without this block, 3 * a would not compile, because Point: Mul<i32> says nothing about i32: Mul<Point>.
Operators take their operands by value
a + b calls add(a, b), which moves both operands. That is harmless for Copy types like Point. For types that own heap data, the left and right operands are consumed, and Rust does not borrow them automatically the way it does for method calls with ..
The usual fix is to implement the operator for references too. Implement the by-reference version with the real logic, and let the by-value version forward to it:
use std::ops::Add;
#[derive(Debug, Clone, PartialEq)]
struct Poly(Vec<i32>);
impl Add for &Poly {
type Output = Poly;
fn add(self, other: Self) -> Poly {
let len = self.0.len().max(other.0.len());
let coeffs = (0..len)
.map(|i| self.0.get(i).copied().unwrap_or(0) + other.0.get(i).copied().unwrap_or(0))
.collect();
Poly(coeffs)
}
}
impl Add for Poly {
type Output = Poly;
fn add(self, other: Poly) -> Poly {
&self + &other
}
}
fn main() {
let a = Poly(vec![1, 2]);
let b = Poly(vec![3, 4, 5]);
let c = &a + &b;
println!("{:?}", c);
let d = a + b;
println!("{:?}", d);
}Both lines print Poly([4, 6, 5]). The standard library follows this pattern: &String + &str is not available, but &i32 + &i32 and &i32 + i32 both are.
Compound assignment is a separate trait
a += b calls AddAssign::add_assign(&mut a, b). It does not fall back to Add. If you implement only Add, then += fails to compile, and the reverse is also true. Implementing the assign form is worth the extra lines for large values, because it can modify in place instead of building a new value.
Index and IndexMut
a[i] is sugar for *a.index(i), and for assignment it uses index_mut. Index returns a reference, so it can only expose data that already exists inside your value. It cannot compute a fresh value. The index type is a trait parameter, so you can use tuples:
use std::ops::{Index, IndexMut};
struct Grid {
width: usize,
cells: Vec<u8>,
}
impl Index<(usize, usize)> for Grid {
type Output = u8;
fn index(&self, (row, col): (usize, usize)) -> &u8 {
&self.cells[row * self.width + col]
}
}
impl IndexMut<(usize, usize)> for Grid {
fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut u8 {
&mut self.cells[row * self.width + col]
}
}
fn main() {
let mut g = Grid { width: 3, cells: vec![0; 6] };
g[(1, 2)] = 7;
println!("{}", g[(1, 2)]);
}IndexMut has Index as a supertrait, so you must implement Index first. An out-of-range index panics inside the underlying Vec, which matches how slices behave.
Operator traits in generic code
Operator traits are ordinary traits, so you can use them as bounds. Add<Output = T> says that adding two T values yields a T:
use std::ops::Add;
fn sum_all<T: Add<Output = T> + Copy>(items: &[T], zero: T) -> T {
let mut total = zero;
for &item in items {
total = total + item;
}
total
}
fn main() {
println!("{}", sum_all(&[1.5, 2.5], 0.0));
println!("{}", sum_all(&[1, 2, 3], 0));
}This prints 4 and 6. The Copy bound is there because total + item moves its operands. Without Copy, you would need T: Add<&'a T> style bounds, which are harder to write.
Common mistakes
- Surprising semantics. Operators should behave like their mathematical meaning. Using
+to append to a log or*to start a process makes code hard to read. Prefer a named method when the meaning is not obvious. - Forgetting the reverse operand order.
Point * i32does not give youi32 * Point. Write both impls if you want both. - Missing reference impls. Code like
&a + &bfails for a type that only implementsAddby value. Add the reference impls, or call.clone()where cloning is acceptable. - Inference ambiguity. When a type has several
Mul<_>impls, a bare literal such as2may not pick one. Annotate the literal, as in3_i32. - Expecting
==instd::ops. Equality and ordering arePartialEqandPartialOrd. Derive them unless you need custom behavior.
Exercise
Why does impl Mul<Point> for i32 compile in your crate even though neither Mul nor i32 is defined there?
Show answer
The orphan rule needs at least one local type among the trait's type parameters or the implementing type, and no uncovered type parameter before it. Point is local and appears as the Rhs parameter of Mul, so the impl is allowed.
Exercise
You implemented Add for a non-Copy type Poly. The line let c = a + b; println!("{:?}", a); fails to compile. What happened, and how can you keep using a?
Show answer
a + b calls Add::add(a, b), which moves both operands, so a is no longer valid. Either implement Add for &Poly and write &a + &b, or use a.clone() + b.
Exercise
You implement Add for Counter but not AddAssign. Does c += other compile? Why or why not?
Show answer
No. += calls AddAssign::add_assign, which is a separate trait, and the compiler does not fall back to Add. You must implement AddAssign yourself.