面试题答案
一键面试#[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);
}
解释:
- 结构体定义:定义了
Rectangle
结构体,包含width
和height
两个u32
类型的字段。 - 实现
PartialEq
trait:重载了==
运算符,通过比较两个矩形的面积来判断是否相等。 - 实现
PartialOrd
trait:重载了比较大小的运算符(<
等),通过比较两个矩形的面积来确定顺序。 - 定义
area
方法:用于计算矩形的面积。 sort_rectangles
函数:接收一个Rectangle
结构体的可变向量,并使用 Rust 标准库的sort
方法对其进行排序,sort
方法会调用我们重载的比较运算符。main
函数:创建了一些矩形,并调用sort_rectangles
函数对它们进行排序,最后打印排序后的结果。