Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 132 ยท Structs, Enums and Traits Basics

Operator Overloading

Overload operators in Rust with std::ops: Add, Sub, Mul, Neg, AddAssign and Index, plus PartialEq, Ord, and implementations for references.

In Rust, a + b is not magic that only works for numbers. It is shorthand for a method call: Add::add(a, b). Every operator maps to a trait in std::ops (or to a comparison trait in std::cmp), and if your type implements the trait, the operator works on it. That is all "operator overloading" means in Rust. There is no special syntax, no way to invent new operators, and no way to change what + does for types you do not own.

This lesson shows how to give your own types arithmetic, negation, compound assignment, indexing and ordering. It builds on traits and on the conversion traits from Display, From and friends. The examples are a 2D vector, a Money type and a tiny matrix, which are the classic cases where operators make code read like the maths it models. After this chapter on traits basics, Generics opens up writing code that works for many types at once.

The operator traits at a glance

Operator Trait Method
a + b Add add(self, rhs)
a - b Sub sub(self, rhs)
a * b Mul mul(self, rhs)
a / b Div div(self, rhs)
a % b Rem rem(self, rhs)
-a Neg neg(self)
!a Not not(self)
a += b AddAssign add_assign(&mut self, rhs)
a[i] Index / IndexMut index(&self, i) / index_mut(&mut self, i)
a == b PartialEq eq(&self, other)
a < b PartialOrd partial_cmp(&self, other)

The &&, || and = operators cannot be overloaded, and neither can the comparison operators return anything but bool.

Add: your first overloaded operator

Each binary operator trait has an output type and, by default, the right-hand side has the same type as Self. Here is Add for a two-dimensional vector.

Rust
use std::ops::Add;

impl Add for Vec2 {
    type Output = Vec2;

    fn add(self, rhs: Vec2) -> Vec2 {
        Vec2 { x: self.x + rhs.x, y: self.y + rhs.y }
    }
}

Output is an associated type (see Associated types): it says what a + b evaluates to. It is often Self, but it does not have to be. Subtracting two timestamps could produce a Duration, for example.

Rust Vec2 with Add, Sub and Neg

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Because Vec2 is Copy, using a several times is fine. Take a moment to notice what the operators do with ownership: a + b calls add(a, b) and moves both operands. For a non-Copy type such as a String or a big matrix, the next sections show how to avoid that.

An operator on a non-Copy type consumes its operands. If you write let c = a + b; and then use a again, the compiler reports use of moved value. Either derive Copy, clone first, or implement the operator for references (below).

Mixing types: Mul by a number

The right-hand side can be any type. Add<Rhs = Self> has a default generic parameter, and you can name another type. Scaling a vector by a number needs Mul<f64>. You can have several Mul impls on the same type, one for each right-hand type.

Multiplying in the other order, 2.0 * v, needs an impl on f64. That is allowed because Vec2 is a type from your crate: the orphan rule only needs one of the trait or the type to be local.

Rust Mul with a scalar, in both orders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Overloading * to mean a dot product is legal, but ask whether a reader will guess it. Many vector libraries use a named method (v.dot(w)) for that reason. A good rule: overload an operator only when the meaning is the obvious mathematical one.

Compound assignment: AddAssign and friends

a += b uses a separate trait, AddAssign, whose method takes &mut self and returns nothing. You do not get it automatically from Add, because modifying in place can be cheaper than building a new value. For a type with heap data, += that reuses the existing buffer is a real performance win.

Rust Money with Add, AddAssign and Sum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Two extras appear in that example. Implementing Sum lets an iterator of Money call .sum(), which is how numbers behave. And because Money derives PartialOrd and Ord, max() works without any further code. Storing money as whole cents in an integer, never as f64, avoids the rounding errors that decimal fractions suffer in binary floating point.

Implementing operators for references

The + on two String-like or matrix-like values should often not eat its inputs. The standard library solves this for numbers by implementing the traits for references too: &a + &b works on &i32. You can do the same for your own types by implementing the trait for &Type.

Here is a Series type that is deliberately not Copy, so you can see the difference. The impl for references holds the real logic, and the by-value impl forwards to it.

Rust Add for values and for references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

If you also want mixed forms such as &a + b, you need more impls (four in total for the full set of reference combinations). Crates usually generate them with a macro. For a small program, pick the forms you actually use.

Index and IndexMut

a[i] is *a.index(i), and in assignment position *a.index_mut(i). The index type is a generic parameter, so a type can be indexed by a usize, by a tuple, or by an enum. A matrix with m[(row, col)] is the usual showcase.

Rust Indexing a matrix with a tuple

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Index returns a reference, because a[i] is a place expression: you can borrow it, assign to it, or call methods on it. That is also why Index cannot return a freshly computed value by copy; if you need that, offer a method like get(r, c) that returns Option<f64>, the way slices have get. The standard library's own indexing panics on bad input, which is why your Index impl may panic too, and you should document it.

Comparison: PartialEq, Eq, PartialOrd and Ord

The comparison operators come from four traits. The first pair is about equality, the second about order.

Trait Adds Promise
PartialEq ==, != symmetric and transitive
Eq (marker) also reflexive: a == a always
PartialOrd <, <=, >, >= partial_cmp may return None
Ord cmp, max, min, clamp a total order: always Less, Equal or Greater

f64 is PartialEq and PartialOrd only, because NAN != NAN. Integers, String, char and tuples of them are Eq and Ord. You need Eq + Ord to use a type as a BTreeMap key or to call .sort() on a Vec of it (floats use .sort_by(|a, b| a.total_cmp(b)) instead).

Deriving all four on a struct compares fields in declaration order, like a dictionary sort. Writing Ord by hand lets you choose a different order, and then PartialOrd should simply forward to it so the two never disagree.

Rust Custom Ord for a task priority queue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The sorted list prints ["a", "c", "b"]: ascending priority, and for the two priority-3 tasks the reversed name rule puts c before b. A BinaryHeap is a max-heap, so the task with the greatest Ord value comes out first: priority 9, then 5, then the two priority-2 tasks with "answer email" ahead of "write docs" because the tie-break reverses the name order. If PartialOrd and Ord disagree, sorting and heaps behave oddly with no error message, so make one delegate to the other.

Common mistakes

The commonest compile error is forgetting that operators move their operands. This program adds two non-Copy values and then uses the first one again.

Rust Using a value after an operator moved it (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler says error[E0382]: borrow of moved value: \a``, pointing at a + b with the label "a moved due to usage in operator" and the note "calling this operator moves the left-hand side": Add::add takes self by value. Fixes: derive Clone and write a.clone() + b, derive Copy if the type is small, or add impl Add for &Bag and write &a + &b.

Other traps to remember:

  • Do not make an operator do something surprising. + on a Path-like type that touches the file system would be a code-review rejection.
  • == on floats is rarely what you want after arithmetic; compare with a tolerance.
  • Mixing up PartialOrd and Ord logic (for example, ordering by one field but deriving PartialEq over all fields) breaks the rule a == b if and only if cmp gives Equal.
  • Operators are plain trait calls, so they inline well. Overloading has no runtime cost beyond what the method body does.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a + b expand to for a type that implements Add?

    Operators are sugar for trait method calls. a + b is Add::add(a, b), and it moves both operands unless they are Copy or references.
  2. 2. Which trait do you implement so that m[(1, 2)] = 3.0 compiles?

    Assigning through an index needs a mutable place, which is what IndexMut::index_mut returns. IndexMut requires Index as a supertrait.
  3. 3. Why does f64 not implement Ord?

    NAN is not equal to itself and has no position relative to other numbers, so f64 has only PartialOrd. Use total_cmp to sort floats.
  4. 4. How can you let callers write &a + &b without consuming a and b?

    Implementing the operator trait for references (impl Add for &Series) lets the operands be borrowed, so the originals remain usable.
  5. 5. A BinaryHeap of your type pops values in which order?

    BinaryHeap is a max-heap: it pops the greatest element according to Ord. Wrap values in Reverse to get a min-heap.

Summary

  • Operators are trait methods: + is Add, - is Sub, * is Mul, unary - is Neg, += is AddAssign, [] is Index and IndexMut.
  • Each operator trait has an associated Output type; the right-hand side can be a different type, such as Mul<f64>.
  • Binary operators take self by value, so they move non-Copy operands. Implement the traits for &Type to avoid that.
  • += is separate from +: implement AddAssign when updating in place is cheaper.
  • PartialEq and PartialOrd power == and <; Eq and Ord add the guarantees needed for sorting, heaps and BTreeMap keys.
  • Make PartialOrd delegate to Ord when you write ordering by hand, and overload an operator only when its meaning is obvious.

Next: Generics