Sub topic 15
When to Overload Operators and When Not To
This chapter assumes you can write impl blocks for traits and know the std::ops traits from earlier in this tutorial: Add, AddAssign, Neg, Index, and the Output associated type. It also assumes you know how Copy and moves affect operands. The chapter has no new syntax. It covers the design question: given that you can overload an operator, should you?
The core test: does the operator keep its meaning?
Rust lets you give + any behavior you like, but readers will still assume + means addition. The simplest test is to read the expression aloud using the operator's ordinary meaning. If a + b reads naturally as "a plus b" and the result behaves like a sum, the overload fits. If you need a comment to explain what + does here, use a named method.
Overloads fit well when the type is a value with an established algebra:
- Geometric and numeric types, such as vectors, matrices, complex numbers, fixed-point numbers, and big integers.
- Quantities with units, such as money, durations, and lengths.
- Containers where
[]means "the element at this position", such as grids and sparse vectors. - Sets or bit sets, where
|,&, and-match the mathematical operations.
The standard library follows the same rule. Instant - Instant gives a Duration, and Instant + Duration gives an Instant. The operand and output types differ, but every combination reads like the arithmetic you would do on paper. PathBuf does not overload / for joining paths. It has join and push, because / there would not match its usual meaning.
A worked example: money that behaves like numbers
The type below overloads only the operators that make sense for money. You can add, subtract, and negate amounts, and you can scale an amount by a count. There is no Mul<Money> for Money, because "dollars times dollars" is not a meaningful quantity here. Leaving an impl out is a design decision: the compiler then rejects the nonsense expression for you.
use std::ops::{Add, Mul, Neg, Sub};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct Money {
cents: i64,
}
impl Money {
fn checked_add(self, rhs: Money) -> Option<Money> {
self.cents.checked_add(rhs.cents).map(|cents| Money { cents })
}
}
impl Add for Money {
type Output = Money;
fn add(self, rhs: Money) -> Money {
Money { cents: self.cents + rhs.cents }
}
}
impl Sub for Money {
type Output = Money;
fn sub(self, rhs: Money) -> Money {
Money { cents: self.cents - rhs.cents }
}
}
impl Neg for Money {
type Output = Money;
fn neg(self) -> Money {
Money { cents: -self.cents }
}
}
impl Mul<i64> for Money {
type Output = Money;
fn mul(self, count: i64) -> Money {
Money { cents: self.cents * count }
}
}
fn main() {
let a = Money { cents: 250 };
let b = Money { cents: 100 };
assert_eq!(a + b, b + a);
assert_eq!((a + b) + a, a + (b + a));
assert_eq!(a - b, a + -b);
assert_eq!(a * 3, Money { cents: 750 });
assert!(a > b);
assert_eq!(Money { cents: i64::MAX }.checked_add(b), None);
}The assertions in main check the laws a reader expects: addition commutes and associates, and subtraction agrees with adding a negation. When you overload an arithmetic operator, write checks like these. They are cheap and they catch the case where an impl drifts away from the meaning of the symbol.
Rules that keep an overload trustworthy
Keep related impls consistent
If a type has both Add and AddAssign, then a += b must leave a equal to what a + b would produce. The easiest way to guarantee that is to implement one in terms of the other. Likewise, Sub should agree with Add and Neg, and PartialEq should agree with PartialOrd. For PartialOrd, partial_cmp returns Some(Ordering::Equal) exactly when == is true. Deriving both traits on the same fields, as Money does, keeps them in step. Hand-written versions are where they drift apart.
Do not hide expensive work or failure
An operator looks cheap. a + b on two Series values allocates a new vector, and a reader cannot tell that from the expression. That is acceptable for numeric code, but document it. Provide reference impls such as &a + &b so callers can avoid moving or cloning their operands, as covered earlier in this tutorial.
Failure is the harder problem. Operators return a plain Output, so they have nowhere to report an error except by panicking. Panics are an accepted convention in two places:
- Integer overflow in debug builds.
Indexwith an out-of-range position.
For anything else, offer a fallible method alongside the operator, as Money::checked_add does. Do not let + quietly saturate, wrap, or return a sentinel value unless your type's documentation says so prominently.
Do not use operators for unrelated actions
Overloading is a misfit when the operator becomes a shorthand for an action that is not the operator's meaning. This pipeline builder compiles and works, but + does not mean "append a stage":
use std::ops::Add;
#[derive(Debug, Default)]
struct Pipeline {
stages: Vec<String>,
}
impl Pipeline {
fn then(mut self, stage: &str) -> Pipeline {
self.stages.push(stage.to_string());
self
}
}
// Compiles, but the symbol hides the intent.
impl Add<&str> for Pipeline {
type Output = Pipeline;
fn add(self, stage: &str) -> Pipeline {
self.then(stage)
}
}
fn main() {
let by_operator = Pipeline::default() + "parse" + "lint";
let by_method = Pipeline::default().then("parse").then("lint");
assert_eq!(by_operator.stages, by_method.stages);
}The method form says what happens, is easy to search for, and has room to grow. You can add then_if, then_all, or a version that returns a Result. A single Add<&str> impl cannot grow like that. Note also that + here is not commutative and has no identity, so it breaks the laws a reader assumes for addition.
Deciding in practice
The next table maps common situations to a choice.
| Situation | Better choice | Reason |
|---|---|---|
| Vector, matrix, or complex number arithmetic | Overload `Add`, `Mul`, and related traits | Matches the math notation readers already know |
| Combining a quantity with a different kind of value | Use `Rhs` and `Output` types that follow the units | `Instant + Duration` gives `Instant` |
| Appending to a collection or builder | Named method such as `push` or `then` | `+` would hide a mutation or an unrelated action |
| Lookup that may miss | `get` returning `Option`, with `Index` only if a panic is acceptable | `Index` cannot return an error |
| Operation that can overflow or fail | `checked_*` method next to the operator | Callers choose how to handle failure |
| Comparison with custom ordering | Implement `PartialOrd` consistently with `PartialEq` | Keeps `<` and `==` coherent |
| Many near-identical impls | A `macro_rules!` macro | Fewer chances for the copies to diverge |
Orphan rule and API shape
You can only implement a foreign trait such as Add when your own type appears in the impl, so you cannot overload + between two standard-library types. That restriction is a design aid. It stops a library from changing how types it does not own behave. If you want operator syntax for a foreign type, wrap it in a newtype and give the wrapper only the operators that fit.
Be deliberate about which impls you publish. Every public operator impl is part of your API, and removing one later is a breaking change. Start with the smallest set that makes your intended code read well, and add reference impls and compound assignment when real callers need them.
Summary of guidelines
- Overload an operator only when the type's behavior matches the operator's conventional meaning.
- Keep
Add,AddAssign,Sub,Neg,PartialEq, andPartialOrdconsistent with each other. - Leave out impls that do not make sense, so the compiler rejects them.
- Provide reference impls when operands are costly to move or clone.
- Offer checked methods for fallible operations, and document any panic.
- Prefer a named method when the operation is an action rather than a calculation.
Exercise
A teammate writes impl Shl<&str> for Logger so that logger << "started" << "ready" appends log lines. Name two reasons this is a poor use of operator overloading, and give the alternative.
Show answer
First, << means shifting bits in Rust, so the symbol does not describe the action, and the expression is an action (writing a line) rather than a calculation. Second, the operator cannot report failure (such as a write error) and has no room to grow, for example to add a log level. The better design is a named method such as logger.info("started"), which can return a Result when writing can fail.
Exercise
You have #[derive(PartialEq)] struct Version(u32, u32) and you hand-write PartialOrd by comparing only the first field. What goes wrong, and how do you fix it?
Show answer
Version(1, 2) == Version(1, 3) is false, but partial_cmp returns Some(Ordering::Equal) for them, so the two traits disagree. Fix it by deriving PartialOrd as well, which compares fields in order, or by writing partial_cmp to compare both fields, for example (self.0, self.1).partial_cmp(&(other.0, other.1)).