当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust Sub用法及代码示例


本文简要介绍rust语言中 Trait core::ops::Sub 的用法。

用法

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

减法运算符 -

请注意,Rhs 默认为 Self,但这不是强制性的。例如, std::time::SystemTime 实现了 Sub<Duration> ,它允许 SystemTime = SystemTime - Duration 形式的操作。

例子

Sub 易处理点

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 });

使用泛型实现Sub

这是使用泛型实现 Sub 特征的相同 Point 结构的示例。

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 });

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 Trait core::ops::Sub。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。