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

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

#[lang = "sub"]

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

The subtraction operator -.

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

use std::ops::Sub;

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

impl Sub for Point { type Output = Point;

fn sub(self, other: Point) -> Point {
    Point {
        x: self.x - other.x,
        y: self.y - other.y,
    }
}

}

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

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

use std::ops::Sub;

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

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

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

}

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

type [Output](#associatedtype.Output)

The resulting type after applying the - operator.

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

Performs the - operation.