Implement Add For Custom Types

Overload the plus operator by implementing Add: the impl consumes operands by value, Copy types duplicate, and Neg mirrors the same contract.

RustData Integrity

Code

rustsnippet
33 lines
use std::ops::{Add, Neg};

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

impl Add for Vec2 {
    type Output = Vec2;

    // Add 按 value 接收 self:两个操作数都被消费(Copy 类型自动复制)
    fn add(self, rhs: Vec2) -> Vec2 {
        Vec2 { x: self.x + rhs.x, y: self.y + rhs.y }
    }
}

impl Neg for Vec2 {
    type Output = Vec2;

    fn neg(self) -> Vec2 {
        Vec2 { x: -self.x, y: -self.y }
    }
}

fn main() {
    let a = Vec2 { x: 1.0, y: 2.0 };
    let b = Vec2 { x: 3.0, y: -1.0 };
    let sum = a + b; // + 号调用 impl Add,操作数按值传入
    println!("sum: {sum:?}");
    println!("flipped: {:?}", -sum);
    println!("a unchanged (Copy): {a:?}");
}

How the snippet works

All of the logic lives in the functions add, neg and main.

Applying it

The primary signature is fn add(self, rhs: Vec2) -> Vec2

The demo output is labeled (sum:, flipped:, a unchanged (Copy):), so every printed line maps back to its originating operation.

Statements that matter

let sum = a + b; // + 号调用 impl Add,操作数按值传入
println!("sum: {sum:?}");
fn add(self, rhs: Vec2) -> Vec2 {
    Vec2 { x: self.x + rhs.x, y: self.y + rhs.y }
}
fn neg(self) -> Vec2 {
    Vec2 { x: -self.x, y: -self.y }
}

Interactive Tools for This Topic

FAQ

What does Implement Add For Custom Types print when run?
The script runs standalone; its 3 labeled outputs include `sum:`, `flipped:`, `a unchanged (Copy):`.