MST
星途 面试题库

面试题:Rust中如何实现基本算术运算符重载

请描述在Rust中为自定义结构体实现加法运算符`+`重载的步骤,并给出一个简单示例代码。
47.1万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
  1. 实现步骤
    • 为自定义结构体实现std::ops::Add trait。
    • 在实现中定义如何对结构体的字段进行加法操作。
  2. 示例代码
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);
}