主题
Trait 与实现
Trait 定义一组方法签名,类型通过实现 Trait 获得对应行为。
定义 Trait
rust
trait Summary {
fn summarize(&self) -> String;
}
为结构体实现 Trait
rust
struct NewsArticle {
headline: String,
author: String,
content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{} by {}", self.headline, self.author)
}
}
使用 Trait 对象多态
rust
fn notify(item: &impl Summary) {
println!("Breaking news! {}", item.summarize());
}
fn main() {
let article = NewsArticle {
headline: String::from("Rust 语言介绍"),
author: String::from("张三"),
content: String::from("Rust 是一种系统级编程语言。"),
};
notify(&article);
}
Trait 约束泛型
rust
fn notify_generic<T: Summary>(item: &T) {
println!("News: {}", item.summarize());
}