MST
星途 面试题库

面试题:Rust结构体自定义比较运算符重载及应用

在Rust中,定义一个结构体 `Rectangle`,有 `width` 和 `height` 两个 `u32` 类型的字段。要求重载比较运算符(如 `==`、`<`),用于比较两个 `Rectangle` 的面积大小。并且编写一个函数,接收一个 `Rectangle` 结构体的向量,使用重载的比较运算符对向量进行排序(按面积从小到大)。
35.2万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl std::cmp::PartialEq for Rectangle {
    fn eq(&self, other: &Self) -> bool {
        self.area() == other.area()
    }
}

impl std::cmp::PartialOrd for Rectangle {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.area().partial_cmp(&other.area())
    }
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn sort_rectangles(rectangles: &mut Vec<Rectangle>) {
    rectangles.sort();
}

你可以这样使用这些代码:

fn main() {
    let mut rectangles = vec![
        Rectangle { width: 3, height: 4 },
        Rectangle { width: 1, height: 6 },
        Rectangle { width: 2, height: 5 },
    ];

    sort_rectangles(&mut rectangles);

    println!("{:?}", rectangles);
}

解释:

  1. 结构体定义:定义了 Rectangle 结构体,包含 widthheight 两个 u32 类型的字段。
  2. 实现 PartialEq trait:重载了 == 运算符,通过比较两个矩形的面积来判断是否相等。
  3. 实现 PartialOrd trait:重载了比较大小的运算符(< 等),通过比较两个矩形的面积来确定顺序。
  4. 定义 area 方法:用于计算矩形的面积。
  5. sort_rectangles 函数:接收一个 Rectangle 结构体的可变向量,并使用 Rust 标准库的 sort 方法对其进行排序,sort 方法会调用我们重载的比较运算符。
  6. main 函数:创建了一些矩形,并调用 sort_rectangles 函数对它们进行排序,最后打印排序后的结果。