From 5626a54d626cfe520ba879c42fc9dd0331c76eb9 Mon Sep 17 00:00:00 2001 From: Jordan Gong Date: Wed, 2 Sep 2020 21:00:12 +0800 Subject: Share behavior with traits --- traits/src/lib.rs | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 traits/src/lib.rs (limited to 'traits/src/lib.rs') diff --git a/traits/src/lib.rs b/traits/src/lib.rs new file mode 100644 index 0000000..a0255ea --- /dev/null +++ b/traits/src/lib.rs @@ -0,0 +1,78 @@ +pub trait Summary { + fn summarize(&self) -> String { + // default implementarion + format!("(Read more from {}...)", self.summarize_author()) + } + + fn summarize_author(&self) -> String { + String::from("Anonymous") + } +} + +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) + } + + // fn summarize_author(&self) -> String { + // format!("{}", self.author) + // } +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + // fn summarize(&self) -> String { + // format!("{}: {}", self.username, self.content) + // } + + fn summarize_author(&self) -> String { + format!("@{}", self.username) + } +} + +// Traits as parameter +// pub fn notify(item: &impl Summary) { +// println!("Breaking news! {}", item.summarize()); +// } + +// Trait bound syntax +pub fn notify(item: &T) { + println!("Breaking news! {}", item.summarize()); +} + +// statements below are equivalent +// pub fn nofity(item1: &impl Summary, item2: Summary) {} +// pub fn nofity(item1: &T, item2: &T) {} + +// use std::fmt::Display; +// multiple bound +// pub fn notify(item: &(impl Summary + Display)) {} +// or +// pub fn notify(item: &T) {} +// where clause +// pub fn notify(item: &T) +// where T: Summary + Display +// {} + +// return impl Trait +fn return_summarizble() -> impl Summary { + Tweet { + username: String::from("horse_ebooks"), + content: String::from("of course, as you probably already know, people"), + reply: false, + retweet: false, + } +} -- cgit v1.2.3