Trait core::ops::Add 1.0.0[−][src]
Expand description
加法运算符 +。
请注意,默认情况下 Rhs 是 Self,但这不是强制性的。
例如,std::time::SystemTime 实现 Add<Duration>,它允许以 SystemTime = SystemTime + Duration 形式进行操作。
Examples
Addable points
use std::ops::Add;
#[derive(Debug, Copy, Clone, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
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使用泛型实现 Add
这是使用泛型实现 Add trait 的同一 Point 结构体的示例。
use std::ops::Add;
#[derive(Debug, Copy, Clone, PartialEq)]
struct Point<T> {
x: T,
y: T,
}
// 请注意,该实现使用关联类型 `Output`。
impl<T: Add<Output = T>> Add for Point<T> {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Self {
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