std::ops::Add - Rust (original) (raw)

Trait std::ops::Add1.0.0 [−] [src]

#[lang = "add"]

pub trait Add<RHS = Self> { type Output; fn add(self, rhs: RHS) -> Self::Output; }

The addition operator +.

Note that RHS is Self by default, but this is not mandatory. For example, std::time::SystemTime implements Add<Duration>, which permits operations of the form SystemTime = SystemTime + Duration.

use std::ops::Add;

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

}

assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, Point { x: 3, y: 3 });Run

Here is an example of the same Point struct implementing the Add trait using generics.

use std::ops::Add;

#[derive(Debug, PartialEq)] struct Point { x: T, y: T, }

impl<T: Add<Output=T>> Add for Point { type Output = Point;

fn add(self, other: Point<T>) -> Point<T> {
    Point {
        x: self.x + other.x,
        y: self.y + other.y,
    }
}

}

assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, Point { x: 3, y: 3 });Run

type [Output](#associatedtype.Output)

The resulting type after applying the + operator.

fn [add](#tymethod.add)(self, rhs: RHS) -> Self::[Output](../../std/ops/trait.Add.html#associatedtype.Output "type std::ops::Add::Output")

Performs the + operation.