Rust中的Trait

mac2022-06-30  18

类似接口,但和php中的trait又有点不一样。

pub trait Summary { fn summarize(&self) -> String; } pub struct NewArticle { pub headline: String, pub author: String, } pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize(&self) -> String { format!("{}: {}", self.username, self.content) } } impl Summary for NewArticle { fn summarize(&self) -> String { format!("{}, by {}", self.headline, self.author) } } fn main() { let tweet = Tweet { username: String::from("horse_ebooks"), content: String::from("of course, as you problem already know, people"), reply: false, retweet: false, }; println!("1 new tweet: {}", tweet.summarize()); let article = NewArticle { headline: String::from("all will be ok"), author: String::from("sky chan"), }; println!("1 new article: {}", article.summarize()); }

转载于:https://www.cnblogs.com/aguncn/p/11409380.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)