Sub topic 12
Overloading operators with std::ops
This chapter assumes you know how to define a trait and implement it for a struct. It also assumes you are comfortable with generic type parameters and with the difference between owned values and references.
Operators are trait methods
In Rust, a + b is shorthand for Add::add(a, b). Each operator maps to a trait in std::ops. If your type implements the trait, the operator works on it. You cannot invent new operators, and you cannot change the meaning of operators on types you don't own beyond what the orphan rule allows.
| Operator | Trait | Method |
|---|---|---|
| `+` | `Add` | `add` |
| `-` | `Sub` | `sub` |
| `*` | `Mul` | `mul` |
| `-x` | `Neg` | `neg` |
| `+=` | `AddAssign` | `add_assign` |
| `a[i]` | `Index` | `index` |
Note that == and < are not in std::ops. They come from PartialEq and PartialOrd in std::cmp.
Implementing Add
Add has an associated type Output for the result, and a generic parameter Rhs for the right-hand side. Rhs defaults to Self. That is why impl Add for Point means "add a Point to a Point".
use std::ops::Add;
#[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 }
}
}
fn main() {
let p = Point { x: 1, y: 2 } + Point { x: 3, y: 4 };
println!("{p:?}");
}This prints Point { x: 4, y: 6 }. The add method takes self by value. Because Point derives Copy, the caller can keep using its operands afterward. Without Copy, a + b would move both values.
Different right-hand types
Because Rhs is a generic parameter, one type can implement Add several times with different right-hand types. Here a Point can be shifted by a plain number.
use std::ops::Add;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Add<i32> for Point {
type Output = Point;
fn add(self, n: i32) -> Point {
Point { x: self.x + n, y: self.y + n }
}
}
fn main() {
println!("{:?}", Point { x: 1, y: 2 } + 10);
}Output is an associated type because each (Self, Rhs) pair has exactly one result type. Rhs is a type parameter because several implementations can coexist.
Compound assignment
+= uses a separate trait, AddAssign. It takes &mut self and returns nothing. Implementing Add does not give you +=.
use std::ops::AddAssign;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl AddAssign for Point {
fn add_assign(&mut self, other: Point) {
self.x += other.x;
self.y += other.y;
}
}
fn main() {
let mut p = Point { x: 1, y: 1 };
p += Point { x: 2, y: 3 };
println!("{p:?}");
}Common errors
- Using a moved value. If your type is not
Copy,a + bconsumesaandb. Implement the trait for references, such asimpl Add for &Matrix, when callers need to keep their values. - Missing the mixed-type impl.
Point + 10compiles, but10 + Pointdoes not. Operands are not swapped. You would needimpl Add<Point> for i32, which is allowed becausePointis local to your crate. - Foreign types on both sides.
impl Add<Vec<u8>> for Stringis rejected by the orphan rule, since neither the trait nor the types are yours.
Exercise
A type Money implements Add and derives Clone but not Copy. The code let c = a + b; println!("{:?}", a); fails to compile. Why, and what are two ways to fix it?
Show answer
Add::add takes self by value, so a + b moves a and b, and a cannot be used afterward. Fix it by deriving Copy for Money (if all fields are Copy), or by writing a.clone() + b. A third option is to implement Add for &Money.