From 97e104176e00844d10a92f887b9f6219c20f1e97 Mon Sep 17 00:00:00 2001 From: laurens Date: Sun, 6 Sep 2020 15:30:44 +0200 Subject: [PATCH] Add traits example --- traits/Cargo.toml | 9 ++++++++ traits/src/main.rs | 57 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 traits/Cargo.toml create mode 100644 traits/src/main.rs diff --git a/traits/Cargo.toml b/traits/Cargo.toml new file mode 100644 index 0000000..11f658a --- /dev/null +++ b/traits/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "traits" +version = "0.1.0" +authors = ["laurens "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/traits/src/main.rs b/traits/src/main.rs new file mode 100644 index 0000000..7bd1864 --- /dev/null +++ b/traits/src/main.rs @@ -0,0 +1,57 @@ +pub trait Summary { + fn summarize_author(&self) -> String; + + fn summarize(&self) -> String { + format!("(Read more from {}...)", self.summarize_author()) + } +} + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle { + // We have to provide an implementation for all methods without default implementation! + fn summarize_author(&self) -> String { + format!("{}", self.author) + } + + fn summarize(&self) -> String { + format!("{}, by {} ({})", self.headline, self.author, self.location) + } +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + // Only implement summarize_author, used by summarize + fn summarize_author(&self) -> String { + format!("{}", self.username) + } +} + +fn main() { + let news_article = NewsArticle { + headline: "My awesome headline".to_string(), + location: "here".to_string(), + author: "me".to_string(), + content: "Something".to_string(), + }; + + let tweet = Tweet { + username: "My cool username".to_string(), + content: "Something in a tweet".to_string(), + reply: false, + retweet: true, + }; + println!("My news article: {}", news_article.summarize()); + println!("My tweet: {}", tweet.summarize()); +}