题目
创建含 width、height 的 Rectangle,实现 area 方法,并派生 Debug 与 PartialEq。输入契约:f64 宽高;输出契约:带 area 方法与 Debug、PartialEq 支持的 Rectangle。公开样例 5.0×3.0 期望 area=15.0。隐藏测试覆盖 0 与 2.5×4.0。
解题思路
struct 定义字段,impl 块定义方法与关联函数;#[derive(Debug, PartialEq)] 让编译器生成调试格式化与相等比较实现。area 借用 self 并返回宽高乘积。
参考实现要点
#[derive(Debug, PartialEq)] struct Rectangle { width: f64, height: f64 };impl Rectangle 中 area(&self) -> f64 返回 self.width * self.height;new(width, height) -> Self 用字段简写构造。方法用点调用,关联函数用 Rectangle::new 调用。
常见错误
原文指出忘记派生 Debug 无法用 {:?} 打印,忘记 PartialEq 无法用 == 比较。另一个坑是 area 写成关联函数却用 rect.area() 调用,或 new 忘记返回 Self;签名与调用方式必须匹配。
验证方式
用 rustc 编译,构造三个样例矩形并断言 area;用 {:?} 打印确认 Debug 生效,用 == 比较两个同尺寸矩形确认 PartialEq 生效。
代码示例
#[derive(Debug, PartialEq)]
struct Rectangle {
width: f64,
height: f64,
}
impl Rectangle {
fn area(&self) -> f64 {
self.width * self.height
}
fn new(width: f64, height: f64) -> Self {
Rectangle { width, height }
}
}