在 Rust 中,可以使用特征(traits)来实现运算符重载。运算符重载是通过实现相应的运算符特征(如 Add、Sub、Mul 等)来完成的。这些特征定义在 std::ops 模块中。下面是一个简单的示例,展示如何为一个自定义结构体实现加法运算符(+)的重载:
代码示例
use std::ops::Add;
// 定义一个结构体 Point 表示二维点
#[derive(Debug, Copy, Clone)]
struct Point {
x: f64,
y: f64,
}
// 为 Point 实现 Add 特征,以支持使用 + 运算符
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
fn main() {
let p1 = Point { x: 1.0, y: 2.0 };
let p2 = Point { x: 3.0, y: 4.0 };
let p3 = p1 + p2; // 使用 + 运算符
println!("{:?}", p3); // 输出:Point { x: 4.0, y: 6.0 }
}
其他运算符
Rust 中的其他运算符也可以通过实现相应的特征来重载,常用的特征包括:
- Sub(-):减法
- Mul(*):乘法
- Div(/):除法
- Rem(%):取余
- Neg(-):一元负号
- Not(!):按位取反
- BitAnd(&):按位与
- BitOr(|):按位或
- BitXor(^):按位异或
- Shl(<<):左移
- Shr(>>):右移
完整代码
#![allow(warnings)]
use std::io;
use std::ops::Add;
use std::error::Error;
use std::boxed::Box;
use std::convert::TryInto;
use std::cmp::Ordering;
use std::cmp::min;
use std::cmp::max;
struct User<'a> {
age: usize,
name: &'a str
}
impl<'a> Add for User<'a> {
// 在 Rust 中,当你实现一个特征时,必须实现该特征的所有关联项。对于 Add 特征,必须实现 Output 关联类型。
type Output = usize;
fn add(self, next: User) -> usize {
self.age + next.age
}
}
fn main() -> Result<(), Box<dyn Error>> {
let u1: User = User {
age: 10,
name: "SQS"
};
let u2: User = User {
age: 20,
name: "sqssqs"
};
print!("{}", u1 + u2);
// 输出30
Ok(())
}