pub trait Summary {
fn summarize_author(&self) -> String;
fn summarize(&self) -> String {
format!("(Default Read more from {}...)", self.summarize_author())
}
}
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize_author(&self) -> String {
format!("@{}", self.username)
}
}
impl Summary for NewsArticle {
fn summarize_author(&self) -> String {
format!("@{}", self.author)
}
fn summarize(&self) -> String {
format!("(NewsArticle Read more from {}...)", self.summarize_author())
}
}
impl Summary for String {
fn summarize_author(&self) -> String {
format!("@{}", &self)
}
fn summarize(&self) -> String {
format!("(Read more from {}...)", self.summarize_author())
}
}
impl Summary for i64 {
fn summarize_author(&self) -> String {
format!("@{}", &self)
}
fn summarize(&self) -> String {
format!("(Read more from {}...)", self.summarize_author())
}
}
pub fn notify(item: impl Summary) {
println!("Breaking news! {}", item.summarize());
}
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."),
};
println!("New article available! {}", article.summarize());
notify(article);
let tweet = Tweet {
username: String::from("horse_ebooks"),
content: String::from("of course, as you probably already know, people"),
reply: false,
retweet: false,
};
println!("1 new tweet: {}", tweet.summarize());
notify(tweet);
notify(1000);
notify(String::from("你好,特质,你很强"));
}
使用trait,语言表达很强啊。 越来越喜欢它了。
总结: 任何类型都可以实现特质。 类似于接口。