面试题答案
一键面试- 实现步骤:
- 为自定义结构体实现
std::ops::Add
trait。 - 在实现中定义如何对结构体的字段进行加法操作。
- 为自定义结构体实现
- 示例代码:
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,
}
}
}
fn main() {
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 3, y: 4 };
let result = p1 + p2;
println!("({},{})", result.x, result.y);
}