TRAITS: Functions taking trait as param + returning type which implements trait

This commit is contained in:
laurens 2020-09-06 16:55:59 +02:00
parent c99a415d16
commit f15cd45d5e

View file

@ -29,7 +29,34 @@ pub struct Tweet {
impl Summary for Tweet { impl Summary for Tweet {
// Only implement summarize_author, used by summarize // Only implement summarize_author, used by summarize
fn summarize_author(&self) -> String { 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, reply: false,
retweet: true, retweet: true,
}; };
println!("My news article: {}", news_article.summarize()); println!("My news article: {}", news_article.summarize());
println!("My tweet: {}", tweet.summarize()); println!("My tweet: {}", tweet.summarize());
println!("Notification:");
notify_version_1(&news_article);
notify_version_2(&tweet);
notify_version_3(&returns_summarizable());
} }