use std::fmt::Display; pub trait Summary { fn summarize_author(&self) -> String; fn summarize(&self) -> String { format!("(Read more...) {}", self.summarize_author()) } } pub struct NewsAritcle { pub headline: String, pub location: String, pub author: String, pub content: String, } impl Summary for NewsAritcle { fn summarize_author(&self) -> String { format!("{}, by {} {}", self.headline, self.author, self.location) } } 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, self.content) } } pub fn notify(item: impl Summary + Display) { println!("Breaking news! {}", item.summarize()); } pub fn notify2(item: T) { println!("Breaking news! {}", item.summarize()); } pub fn notify3(item: T) where T: Summary + Display, { println!("Breaking news! {}", item.summarize()); } pub fn notify5() -> impl Summary where T: Summary, { Tweet { username: String::from("今日说法"), content: String::from("今日说法"), reply: true, retweet: false, } } struct Pair { x: T, y: T, } impl Pair { fn new(x: T, y: T) -> Self { Self { x, y } } } impl Pair { fn cmp_display(&self) { println!("{}, {}", self.x, self.y); } }