什么是trait?如果了解Java语言的话,你就可以把trait理解为Java的interface接口
-
定义
pub trait Summarizable { fn summary(&self) -> String; }
-
定义struct
pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String }
-
实现trait
impl Summarizable for NewsArticle { fn summary(&self) -> String { format!("{}, by {} ({})", self.headline, self.author, self.location) }
-
调用
fn main() { let article = NewsArticle { headline: String::from("headline"), location: String::from("location"), author: String::from("author"), content: String::from("content"), }; println!("{}", article.summary()); }
这里 NewsArticle 的实例就有了Summarizable定义的summary的方法了。
详细关于trait的使用请参考参考链接参考链接
网友评论