100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Rust

Operator Overloading in Rust

Rust lets custom types support operators like + and - by implementing traits from std::ops.

Traits & GenericsIntermediate7 min readJul 8, 2026
Analogies

Introduction

Operator overloading lets you define what operators like +, -, *, and == mean for your own types. Rust exposes this through the traits in the std::ops module, so there is no special syntax — overloading an operator is simply implementing the corresponding trait, such as Add for +. This keeps the mechanism consistent with the rest of the trait system rather than being a separate language feature.

🏏

Cricket analogy: Just as the DRS review process follows the same appeal mechanism as a normal umpire decision, Rust makes '+' just an ordinary trait call (Add) rather than a special-cased rule only for built-in types.

Syntax

rust
use std::ops::Add;

#[derive(Debug, Clone, Copy)]
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,
        }
    }
}

Explanation

Implementing Add for Point defines an associated type Output, which is the result type of the operation, and an add method that the + operator calls under the hood. Once implemented, writing point_a + point_b compiles to point_a.add(point_b). Other operators follow the same pattern: Sub for -, Mul for *, Neg for unary -, Index for [], and PartialEq for ==. Each trait defines the exact method signature you must implement to hook into the operator.

🏏

Cricket analogy: Writing battingAvg + strikeRate compiles down to battingAvg.add(strikeRate) under the hood, the same way an analyst's 'combined rating' formula is really just calling a defined scoring method, not built-in magic.

Example

rust
use std::ops::Add;

#[derive(Debug, Clone, Copy)]
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 p1 = Point { x: 1, y: 2 };
    let p2 = Point { x: 3, y: 4 };
    let p3 = p1 + p2;
    println!("{:?}", p3);
}

Output

text
Point { x: 4, y: 6 }

Key Takeaways

  • Operator overloading in Rust is implemented via traits in std::ops, not dedicated syntax.
  • impl Add for Point with type Output = Point lets you use + on Point values.
  • Other operators map to traits like Sub, Mul, Neg, Index, and PartialEq.
  • The + operator desugars to a call of the trait's method, e.g. add.
  • You can overload operators between different types by choosing different Output/RHS types.

Practice what you learned

Was this page helpful?

Topics covered

#Rust#RustProgrammingStudyNotes#Programming#OperatorOverloadingInRust#Operator#Overloading#Syntax#Explanation#StudyNotes#SkillVeris