trait
code:trait.rs
pub trait Summary {
fn summarize(&self) -> String;
}
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}
pub fn notify(item: &impl Summary) {
println!("Breaking news! {}", item.summarize());
}
// 以下のように書いてもよい
pub fn notify<T: Summary>(item: &T) {
println!("Breaking news! {}", item.summarize());
}
// 以下のように書いてもよい
pub fn notify<T>(item: &T) where T: Summary {
}
デフォルト実装を提供できる
code:.rs
pub trait Summary {
fn summarize(&self) -> String {
// "(もっと読む)"
String::from("(Read more...)")
}
}
code:.rs
pub fn notify(item: &(impl Summary + Display)) {