pub trait Sub<Rhs = Self> {
type Output;
// Required method
fn sub(self, rhs: Rhs) -> Self::Output;
}Expand description
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.
§Examples
§Subtractable points
use std::ops::Sub;
#[derive(Debug, Copy, Clone, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Sub for Point {
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Self {
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 });§Implementing Sub with generics
Here is an example of the same Point struct implementing the Sub trait
using generics.
use std::ops::Sub;
#[derive(Debug, PartialEq)]
struct Point<T> {
x: T,
y: T,
}
// Notice that the implementation uses the associated type `Output`.
impl<T: Sub<Output = T>> Sub for Point<T> {
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
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 });Required Associated Types§
Required Methods§
Implementors§
Source§impl Sub for Dec19x19
§Tests
check!( [Dec19x19::sub, Dec19x19::checked_sub] {
(Dec19x19::MIN + Dec19x19!(1), Dec19x19!(1)) => Dec19x19::MIN,
(-Dec19x19::SMALLEST_STEP, Dec19x19::MIN) => Dec19x19::MAX,
(Dec19x19::MIN, Dec19x19::SMALLEST_STEP) => FAIL,
(Dec19x19::MIN, Dec19x19!(1)) => FAIL,
(Dec19x19!(0), Dec19x19::MIN) => FAIL,
});
§Fuzzy
fuzzy2::<Dec19x19, BigDecimal>(Series::new(0..=18, 0..=19), Series::new(0..=18, 0..=19),
|(f1, b1), (f2, b2)| should_eq(f1 - f2, b1 - b2)
);
impl Sub for Dec19x19
§Tests
check!( [Dec19x19::sub, Dec19x19::checked_sub] {
(Dec19x19::MIN + Dec19x19!(1), Dec19x19!(1)) => Dec19x19::MIN,
(-Dec19x19::SMALLEST_STEP, Dec19x19::MIN) => Dec19x19::MAX,
(Dec19x19::MIN, Dec19x19::SMALLEST_STEP) => FAIL,
(Dec19x19::MIN, Dec19x19!(1)) => FAIL,
(Dec19x19!(0), Dec19x19::MIN) => FAIL,
});§Fuzzy
fuzzy2::<Dec19x19, BigDecimal>(Series::new(0..=18, 0..=19), Series::new(0..=18, 0..=19),
|(f1, b1), (f2, b2)| should_eq(f1 - f2, b1 - b2)
);