struct Point {
x: i32,
y: i32,
}
impl std::ops::Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl
块的作用
impl
块用于为结构体、枚举或 trait 提供具体的实现。在上述代码中,impl std::ops::Add for Point
表示为 Point
结构体实现 std::ops::Add
这个 trait。通过 impl
块,我们可以在 Point
结构体上定义与 Add
trait 相关的方法,这里就是定义了 add
方法,使得 Point
结构体能够使用 +
运算符。
std::ops::Add
特征的作用
std::ops::Add
是 Rust 标准库中定义的一个 trait,用于重载 +
运算符。当我们为 Point
结构体实现 Add
trait 时,实际上是告诉 Rust 编译器如何对 Point
结构体的实例进行加法操作。在实现 Add
trait 时,必须指定 Output
关联类型,这里表示 +
运算的结果类型,同时要实现 add
方法,定义具体的加法逻辑。这样,在代码中就可以像对基本类型一样对 Point
结构体实例使用 +
运算符。