From f15cd45d5e08b53cceefc90be4a57da25aecc6a9 Mon Sep 17 00:00:00 2001 From: laurens Date: Sun, 6 Sep 2020 16:55:59 +0200 Subject: [PATCH] TRAITS: Functions taking trait as param + returning type which implements trait --- traits/src/main.rs | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/traits/src/main.rs b/traits/src/main.rs index c9f26de..d52d5d0 100644 --- a/traits/src/main.rs +++ b/traits/src/main.rs @@ -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(item: &T) { + println!("Breaking news! {}", item.summarize()); +} + +fn notify_version_3(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()); }