RRust By Example
advancedTraits

Operator Overloading

Implement operator traits like Add, Mul, Display.

Operator Overloading

Implement operator traits like Add, Mul, Display.

Difficulty

Advanced

Code

rust
use std::ops::{Add, Mul};

#[derive(Debug, Clone, Copy)]
struct Vec2 { x: f64, y: f64 }

impl Add for Vec2 {
    type Output = Vec2;
    fn add(self, other: Vec2) -> Vec2 {
        Vec2 { x: self.x + other.x, y: self.y + other.y }
    }
}

impl Mul<f64> for Vec2 {
    type Output = Vec2;
    fn mul(self, scalar: f64) -> Vec2 {
        Vec2 { x: self.x * scalar, y: self.y * scalar }
    }
}

fn main() {
    let a = Vec2 { x: 1.0, y: 2.0 };
    let b = Vec2 { x: 3.0, y: 4.0 };
    println!("{:?}", a + b);
    println!("{:?}", a * 2.0);
}

Explanation

This example demonstrates how to use operator overloading in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the traits category to build a complete understanding of this topic.

More Traits Examples