Rust进阶[part5]_trait
trait概述
在 Rust 中,trait
是一种定义共享行为的方式。它类似于其他语言中的接口,允许我们定义一组方法签名,然后让不同的类型去实现这些方法。通过 trait
,我们可以实现多态性,即不同类型可以以统一的方式处理。
普通实现
- 使用
trait
关键字来声明一个特征 summary
是特征名- 在大括号中定义了该特征的所有方法
// 定义一个 trait
trait Summary {fn summarize(&self) -> String;
}// 定义一个结构体
struct NewsArticle {headline: String,location: String,author: String,content: String,
}// 为 NewsArticle 结构体实现 Summary trait
impl Summary for NewsArticle {fn summarize(&self) -> String {format!("{}, by {} ({})", self.headline, self.author, self.location)}
}// 定义另一个结构体
struct Tweet {username: String,content: String,reply: bool,retweet: bool,
}// 为 Tweet 结构体实现 Summary trait
impl Summary for Tweet {fn summarize(&self) -> String {format!("{}: {}", self.username, self.content)}
}fn main() {let article = NewsArticle {headline: String::from("Penguins win the Stanley Cup Championship!"),location: String::from("Pittsburgh, PA, USA"),author: String::from("Iceburgh"),content: String::from("The Pittsburgh Penguins once again are the best \hockey team in the NHL."),};let tweet = Tweet {username: String::from("horse_ebooks"),content: String::from("of course, as you probably already know, people"),reply: