Sub in std::ops - Rust (original) (raw)
Trait std::ops::Sub
pub trait Sub<Rhs = Self> {
type Output;
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
.
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 });
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 });
The resulting type after applying the -
operator.
Performs the -
operation.
assert_eq!(12 - 1, 11);
impl<'_, '_> Sub<&'_ i8> for &'_ i8
impl<'_, '_> Sub<&'_ u8> for &'_ u8
impl<'_, T, const LANES: usize> Sub<&'_ Simd<T, LANES>> for Simd<T, LANES> where
T: SimdElement,
Simd<T, LANES>: Sub<Simd<T, LANES>>,
LaneCount: SupportedLaneCount,
<Simd<T, LANES> as Sub<Simd<T, LANES>>>::Output == Simd<T, LANES>,
impl<'_, T, const LANES: usize> Sub<Simd<T, LANES>> for &'_ Simd<T, LANES> where
T: SimdElement,
Simd<T, LANES>: Sub<Simd<T, LANES>>,
LaneCount: SupportedLaneCount,
<Simd<T, LANES> as Sub<Simd<T, LANES>>>::Output == Simd<T, LANES>,
impl<'lhs, 'rhs, T, const LANES: usize> Sub<&'rhs Simd<T, LANES>> for &'lhs Simd<T, LANES> where
T: SimdElement,
Simd<T, LANES>: Sub<Simd<T, LANES>>,
LaneCount: SupportedLaneCount,
<Simd<T, LANES> as Sub<Simd<T, LANES>>>::Output == Simd<T, LANES>,