trait
1. trait 作用
2. trait 使用
2.1 定义一个 trait
pub trait Summary {
fn summarize(&self) -> String;
}// Article online
pub mod online {
pub trait Summary {
fn summary(&self) -> String;
}
// News article type
#[derive(Debug)]
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
// Tweet limits words of 0-280
#[derive(Debug)]
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for NewsArticle {
fn summary(&self) -> String {
format!("{}, by {} {}", self.headline, self.author, self.location)
}
}
impl Summary for Tweet {
fn summary(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
}2.2 默认实现
3. Trait bound
通过 where 简化代码
Last updated