实现说明
除了函数 area、label、describe、main,文件里再无其他定义。
使用要点
- 执行文件,
main会按顺序走完describe。
常见问题
「定义 trait 并为多个类型实现」这个示例怎么运行?
直接执行即可——程序只依赖运行时自身。
签名一览:fn area(&self) -> f64;
核心语句
fn label(&self) -> String { format!("rect {}x{}", self.w, self.h) }
fn area(&self) -> f64 { std::f64::consts::PI * self.r * self.r }
fn area(&self) -> f64 { self.w * self.h }
代码示例
// 声明 trait:必需方法 + 可选默认方法
trait Area {
fn area(&self) -> f64;
fn label(&self) -> String {
String::from("shape")
}
}
struct Rect { w: f64, h: f64 }
struct Circle { r: f64 }
// 为多个类型分别 impl:覆盖默认方法可选
impl Area for Rect {
fn area(&self) -> f64 { self.w * self.h }
fn label(&self) -> String { format!("rect {}x{}", self.w, self.h) }
}
impl Area for Circle {
fn area(&self) -> f64 { std::f64::consts::PI * self.r * self.r }
// label 沿用默认实现
}
// 泛型函数:T: Area 约束接受任何实现 types
fn describe<T: Area>(s: &T) {
println!("{} -> {:.2}", s.label(), s.area());
}
fn main() {
describe(&Rect { w: 3.0, h: 4.0 });
describe(&Circle { r: 1.0 });
}