Sub topic 15
When to overload operators and when not to
This chapter assumes you can implement Add, know what Output and Rhs do, and have seen AddAssign, PartialOrd, and the orphan rule. Those chapters covered how to overload. This one covers whether you should.
The test: would a reader guess the meaning?
An overloaded operator hides a function call behind one character. The reader has no name to read, so the meaning has to be obvious. Ask this before writing impl Add:
- Does the operation match the usual meaning of the symbol?
- Would two people guess the same result?
- Is the cost what a reader expects from an operator?
If any answer is no, write a named method instead.
Good fits and poor fits
| Operation | Verdict | Reason |
|---|---|---|
| `Vec2 + Vec2` | Good | Matches vector addition. |
| `Vec2 * f64` | Good | Scaling is the standard meaning. |
| `Vec2 * Vec2` | Poor | Dot product, cross product, and per-component product are all plausible. |
| `a == b` on a type with a float tolerance | Risky | `PartialEq` should be an exact, transitive comparison. |
| `Grid[(r, c)]` | Good | Same shape as slice indexing. |
| `queue << item` for pushing | Poor | Surprising outside C++ streams. A `push` method is clearer. |
The standard library follows this rule. Duration + Duration is an operator, but string concatenation uses String + &str only because appending is the obvious reading.
Keep related operators consistent
Users expect a += b to give the same result as a = a + b. The simplest way to guarantee this is to write the compound form in terms of the binary one.
use std::ops::{Add, AddAssign};
#[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 }
}
}
impl AddAssign for Vec2 {
fn add_assign(&mut self, rhs: Vec2) {
*self = *self + rhs;
}
}
impl Vec2 {
// A named method: "multiplication" of two vectors is ambiguous.
fn dot(self, other: Vec2) -> f64 {
self.x * other.x + self.y * other.y
}
}
fn main() {
let a = Vec2 { x: 1.0, y: 2.0 };
let b = Vec2 { x: 3.0, y: 4.0 };
let mut c = a;
c += b;
assert_eq!(c, a + b);
assert_eq!(a.dot(b), 11.0);
}For types that are not Copy, delegating can cost an extra allocation. In that case, implement the compound form in place and have the binary form call it.
The same consistency applies to comparisons. If you implement PartialOrd by hand, make partial_cmp agree with PartialEq. When partial_cmp returns Some(Equal), == must return true.
Other rules to follow
- No hidden side effects. An operator should not print, lock, or touch the network.
- Panics only where convention allows.
Indexpanics on out-of-bounds access, as slices do. AnAddthat panics on bad input is a surprise. Preferchecked_add-style methods for fallible math. - Visible cost. Adding two large matrices with
&a + &bis fine if the reference impl signals that nothing is moved. Hiding an expensive operation behind+in a hot loop is not. - Work within the orphan rule. You cannot implement
Addfor two foreign types. Wrap one in a newtype, and overload only if the wrapper has a clear meaning.
Exercise
A teammate proposes impl Mul for Vec2 that returns the dot product as f64. Give two reasons to prefer a different design, and name the alternative.
Show answer
Reason 1: Vec2 * Vec2 is ambiguous, since readers may expect a component-wise product or a cross product, so the symbol has no single obvious meaning. Reason 2: it breaks the pattern where Mul between two values of a type returns that type, which makes generic code bounded by Mul<Output = T> misbehave or fail to compile for Vec2. Use a named method such as dot, and keep Mul<f64> for scaling.