skip to content

In Rust, how do you make `a + b`, `a += b`, `-a` and `2.0 * a` compile for a `Vector3` type, and why does `a + b` move `a`?

level: middleimportance: should knowfreq 50%

answer

  1. operators are traits
  2. std::ops, Output associated type
  3. each operator form is its own trait
  4. add takes self by value

basics

~20 s

Each operator is a std::ops trait: Add (with an Output type) for +, AddAssign for +=, Neg for unary minus, and Mul<Vector3> for f32 for 2.0 * a. Add::add takes self by value, so a non-Copy operand moves.

solid answer

~40 s

Rust overloads operators only through traits: `a + b` is `Add::add(a, b)`, so you write `impl Add for Vector3` with `type Output = Vector3`; `Rhs` defaults to `Self`, and `impl Mul<f32> for Vector3` adds `a * 2.0`. Every form is a separate trait: `+=` needs `AddAssign` (E0368 without it), unary `-` needs `Neg` (E0600), and `2.0 * a` needs `impl Mul<Vector3> for f32`, which the orphan rule accepts because `Vector3` is a local type. `add` takes `self` by value, so a non-`Copy` left operand is moved and using it again is E0382. A three-`f32` `Vector3` should simply derive `Clone, Copy`; a type that is expensive to copy implements the operator for references, `impl Add<&Vector3> for &Vector3`, so `&a + &b` borrows instead.

code

rust · 32 lines
rust
use std::ops::{Add, AddAssign, Mul, Neg};

#[derive(Debug, Clone, Copy, PartialEq)]
struct Vector3 { x: f32, y: f32, z: f32 }

impl Add for Vector3 {
    type Output = Vector3;
    fn add(self, r: Vector3) -> Vector3 { Vector3 { x: self.x + r.x, y: self.y + r.y, z: self.z + r.z } }
}
impl Mul<f32> for Vector3 {
    type Output = Vector3;
    fn mul(self, k: f32) -> Vector3 { Vector3 { x: self.x * k, y: self.y * k, z: self.z * k } }
}
impl Mul<Vector3> for f32 {
    type Output = Vector3;
    fn mul(self, v: Vector3) -> Vector3 { v * self }
}
impl Neg for Vector3 {
    type Output = Vector3;
    fn neg(self) -> Vector3 { Vector3 { x: -self.x, y: -self.y, z: -self.z } }
}
impl AddAssign for Vector3 {
    fn add_assign(&mut self, r: Vector3) { *self = *self + r; }
}

fn main() {
    let gravity = Vector3 { x: 0.0, y: -9.8, z: 0.0 };
    let mut velocity = Vector3 { x: 1.0, y: 0.0, z: 0.0 };
    velocity += gravity * 0.5;
    let kick = -velocity + 2.0 * gravity;
    println!("{velocity:?} {kick:?} {gravity:?}");
}

go deeper

for a junior

Recall that each operator maps to a std::ops trait and method, and be able to write impl Add for a small struct with type Output set.

for a middle

Explain why add takes self by value, what E0382 after a + b means, why += needs AddAssign, and how Rhs and Output let mixed types combine.

for a senior

Decide between Copy and reference impls by cost, keep operator semantics unsurprising, and know the orphan rule allows impl Mul<Vector3> for f32.

for a principal

Weigh how much operator surface a math type should expose: every operand combination is an impl to maintain, so pick the set callers need and generate the rest consistently.

## Operators are trait calls Rust has no special syntax for declaring an operator. Every overloadable operator is a **trait** in `std::ops` (re-exported from `core::ops`), and the compiler rewrites the operator expression into a call of that trait's method. If the trait is not implemented for the operand types, the expression does not compile. | Expression | Trait | Method signature | |---|---|---| | `a + b` | `Add<Rhs = Self>` | `fn add(self, rhs: Rhs) -> Self::Output` | | `a - b` | `Sub<Rhs = Self>` | `fn sub(self, rhs: Rhs) -> Self::Output` | | `a * k` | `Mul<Rhs = Self>` | `fn mul(self, rhs: Rhs) -> Self::Output` | | `-a` | `Neg` | `fn neg(self) -> Self::Output` | | `!a` | `Not` | `fn not(self) -> Self::Output` | | `a += b` | `AddAssign<Rhs = Self>` | `fn add_assign(&mut self, rhs: Rhs)` | Two details of these signatures drive everything else: - **`Output` is an associated type.** The implementer chooses the result type, so subtracting two points may return a displacement vector rather than another point. - **`Rhs` is a type parameter with a default of `Self`.** Writing `impl Add for Vector3` means `impl Add<Vector3> for Vector3`; writing `impl Mul<f32> for Vector3` gives you scaling by a scalar, and a type may implement `Mul` several times with different `Rhs` types. ## Implementing the Vector3 operators A physics engine's `Vector3` of three `f32` fields is a textbook case. The snippet in this question's code example implements `Add`, `Mul<f32>`, `Mul<Vector3> for f32`, `Neg` and `AddAssign`, then integrates a velocity with `velocity += gravity * 0.5`. Each piece answers one compile error you would otherwise meet: 1. Without `Add`, `a + b` fails with **E0369** ("cannot add `Vector3` to `Vector3`"). 2. Without `AddAssign`, `a += b` fails with **E0368** ("binary assignment operation `+=` cannot be applied to type `Vector3`"). std has no blanket impl that derives `+=` from `+`, because `add_assign` takes `&mut self` and updates in place, which is a different contract. 3. Without `Neg`, `-a` fails with **E0600** ("cannot apply unary operator `-` to type `Vector3`"); the same error appears for `-n` on a `u32`, because unsigned integers do not implement `Neg`. 4. Without `impl Mul<Vector3> for f32`, `2.0 * a` fails with E0369. Writing that impl is allowed even though both `Mul` and `f32` come from std: the orphan rule accepts it because the local type `Vector3` appears as the trait's type argument. std provides **no derive** for arithmetic operators; `#[derive(Add)]` fails with "cannot find derive macro `Add` in this scope". You write the impls by hand or with your own declarative macro. ## Ownership: why `a + b` moves `add`, `sub`, `mul`, `neg` and `not` all take `self` by value, and the binary ones take `rhs` by value too. For a `Copy` type that is invisible: the operands are copied bitwise. For a type that is not `Copy`, the operator consumes both operands. rustc 1.99.1 reports the follow-up use as **E0382**, "borrow of moved value: `a`", with the label "`a` moved due to usage in operator" and the note "calling this operator moves the left-hand side". There are two repairs, and the choice is about cost: - **Derive `Clone, Copy`** when the type is small plain data. Three `f32` fields copy as cheaply as a pointer pair, so a `Vector3` should almost always be `Copy`. - **Implement the operator for references** when copying is expensive: `impl Add<&Vector3> for &Vector3 { type Output = Vector3; ... }` lets `&a + &b` borrow both operands and leave them usable. Each combination (`T + T`, `&T + &T`, `T + &T`, `&T + T`) is its own impl; a common pattern writes the reference version once and forwards the others to it. std does exactly this for the primitive numbers, which is why `1 + &2` and `&1.5 + &2.0` compile. ## What belongs in an operator impl - Keep the mathematical meaning. `+` on a vector should be component-wise addition, not "append to a list"; readers trust operators to be cheap and side-effect free. - Keep the result type honest through `Output` instead of returning a wrapper the caller must unwrap. - Avoid panicking in arithmetic operators unless the primitive would (integer overflow in debug builds, division by zero). - Comparison operators (`==`, `<`) are not in `std::ops` at all; they come from the equality and ordering traits, covered in the lesson on equality, ordering and hashing.

  • Why doesn't implementing `Add` give a Rust type `+=` for free?
    std has no blanket impl from `Add` to `AddAssign`. `add_assign` takes `&mut self` and updates in place, while `add` consumes its operands and returns a new value, so they are separate contracts. Without `AddAssign`, `a += b` fails with E0368. For a `Copy` type the impl is one line, `*self = *self + rhs`.
  • How do you let `&a + &b` work for a Rust type that is expensive to copy?
    Write `impl Add<&Vector3> for &Vector3` with `type Output = Vector3`; the method receives two shared references and builds a new value, so neither operand moves. `T + T`, `T + &T` and `&T + T` are separate impls; forward them to the reference version by hand or with a small declarative macro, the way std forwards reference forms for primitive numbers.
  • Can a Rust operator return a type different from its operands?
    Yes. `Output` is an associated type the implementer chooses, so `impl Sub for Point3 { type Output = Vector3; }` makes a point minus a point a displacement, and `impl Mul<f32> for Vector3` mixes operand types. The only rule is one `Output` per `(Self, Rhs)` pair.

  • Implementing Add automatically makes += work on the same type.
  • a + b only borrows its operands, so a non-Copy a stays usable afterwards.
  • 2.0 * v is impossible because f32 is a foreign type.
  • std's #[derive(Add)] generates component-wise addition for structs.
  • Add's right-hand side must always be the same type as Self.