实现了std::ops::Add trait 能够直接使用+进行操作,相当于重载了+。下面看一下它的定义:
trait Add<RHS=Self> {
type Output;
fn add(self, rhs: RHS) -> Self::Output;
}
下面通过一个简单的例子实现Add trait:
use std::ops::Add;
#[derive(Debug)]
struct Complex<T> {
re: T,
im: T,
}
impl<T> Add for Complex<T>
where
T: Add<Output = T>,
{
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Complex {
re: self.re + rhs.re,
im: self.im + rhs.im,
}
}
}
fn main() {
println!("{:?}", Complex { re: 1, im: 1 } + Complex { re: 2, im: 2 });
}
// 输出: Complex { re: 3, im: 3 }
上需要注意的是类型T本身也需要实现Add trait,才能进行加法。
下面看一个复杂点的例子:
use std::fmt::Display;
use std::ops::Add;
#[derive(Debug)]
struct Any<T> {
a: T,
b: T,
}
impl<L, R> Add<Any<R>> for Any<L>
where
L: Display,
R: Display,
{
type Output = Any<String>;
fn add(self, rhs: Any<R>) -> Self::Output {
Any {
a: format!("{}{}", self.a, rhs.a),
b: format!("{}{}", self.b, rhs.b),
}
}
}
fn main() {
println!(
"{:?}",
Any {
a: "number a: ".to_owned(),
b: "number b: ".to_owned()
} + Any { a: 2, b: 2 }
);
}
// 输出: Any { a: "number a: 2", b: "number b: 2" }
上面Any类型通过实现Add trait,能够达到生成字符串的功能。