How to Use Operator Overloading in Rust (Add, Mul, etc.)

Overload Rust operators by implementing specific traits like Add or Mul from the std::ops module for your custom types.

You overload operators in Rust by implementing specific traits from std::ops for your custom type.

use std::ops::Add;

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; // Uses the Add trait implementation
    println!("{}", p3.x + p3.y); // Prints 10
}

Replace Add with Mul, Sub, Div, or other traits in std::ops to overload different operators.