TRAITS: Functions taking trait as param + returning type which implements trait
This commit is contained in:
parent
c99a415d16
commit
f15cd45d5e
1 changed files with 34 additions and 1 deletions
|
|
@ -29,7 +29,34 @@ pub struct Tweet {
|
|||
impl Summary for Tweet {
|
||||
// Only implement summarize_author, used by summarize
|
||||
fn summarize_author(&self) -> String {
|
||||
format!("{}", self.username)
|
||||
format!("@{}", self.username)
|
||||
}
|
||||
}
|
||||
|
||||
// Shorter version but with its limitations when having multiple args
|
||||
fn notify_version_1(item: &impl Summary) {
|
||||
println!("Breaking news! {}", item.summarize());
|
||||
}
|
||||
|
||||
fn notify_version_2<T: Summary>(item: &T) {
|
||||
println!("Breaking news! {}", item.summarize());
|
||||
}
|
||||
|
||||
fn notify_version_3<T>(item: &T)
|
||||
where T: Summary
|
||||
{
|
||||
println!("Breaking news! {}", item.summarize());
|
||||
}
|
||||
|
||||
// Returning a type that implements the summary trait
|
||||
fn returns_summarizable() -> impl Summary {
|
||||
Tweet {
|
||||
username: String::from("horse_ebooks"),
|
||||
content: String::from(
|
||||
"of course, as you probably already know, people",
|
||||
),
|
||||
reply: false,
|
||||
retweet: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -47,6 +74,12 @@ fn main() {
|
|||
reply: false,
|
||||
retweet: true,
|
||||
};
|
||||
|
||||
println!("My news article: {}", news_article.summarize());
|
||||
println!("My tweet: {}", tweet.summarize());
|
||||
|
||||
println!("Notification:");
|
||||
notify_version_1(&news_article);
|
||||
notify_version_2(&tweet);
|
||||
notify_version_3(&returns_summarizable());
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue