diff options
author | garhve <git@garhve.com> | 2023-01-03 19:05:48 +0800 |
---|---|---|
committer | garhve <git@garhve.com> | 2023-01-03 19:05:48 +0800 |
commit | faa108dc5c84f5c4aecee35a2f490eeedc85cb0d (patch) | |
tree | 30193abd2dceb21aab9a536f786f959dedd018f1 /rust/theBook/chapter-10-generic-types-traits-lifetimes/traits | |
parent | 0e89468188b9d347495dad5b98af137e5f477432 (diff) |
add files
Diffstat (limited to 'rust/theBook/chapter-10-generic-types-traits-lifetimes/traits')
3 files changed, 60 insertions, 0 deletions
diff --git a/rust/theBook/chapter-10-generic-types-traits-lifetimes/traits/Cargo.toml b/rust/theBook/chapter-10-generic-types-traits-lifetimes/traits/Cargo.toml new file mode 100644 index 0000000..460f45f --- /dev/null +++ b/rust/theBook/chapter-10-generic-types-traits-lifetimes/traits/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "traits" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/rust/theBook/chapter-10-generic-types-traits-lifetimes/traits/src/lib.rs b/rust/theBook/chapter-10-generic-types-traits-lifetimes/traits/src/lib.rs new file mode 100644 index 0000000..45c93c8 --- /dev/null +++ b/rust/theBook/chapter-10-generic-types-traits-lifetimes/traits/src/lib.rs @@ -0,0 +1,29 @@ +pub trait Summary { + fn summarize (&self) -> String; +} + +pub struct NewsArticle { + pub author: String, + pub headline: String, + pub location: String, + pub content: String, +} + +impl Summary for NewsArticle { + fn summarize(&self) -> String { // return String ownership. &self means self: &Self + format!("{} by {} ({})", self.headline, self.author, self.location) + } +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub retweet: bool, + pub reply: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { // &Self is the type owns impl + format!("{}: {}",self.username, self.content) + } +} diff --git a/rust/theBook/chapter-10-generic-types-traits-lifetimes/traits/src/main.rs b/rust/theBook/chapter-10-generic-types-traits-lifetimes/traits/src/main.rs new file mode 100644 index 0000000..f0229a0 --- /dev/null +++ b/rust/theBook/chapter-10-generic-types-traits-lifetimes/traits/src/main.rs @@ -0,0 +1,23 @@ +use traits::{Tweet, Summary, NewsArticle}; + +fn main() { + let tweet = Tweet { + username: String::from("horse_ebook"), + content: String::from( + "of course, as you probably already know, people." + ), + reply: false, + retweet: false, + }; + + println!("1 new tweet: {}", tweet.summarize()); + + let article = NewsArticle { + author: String::from("garhve"), + headline: String::from("how to die"), + location: String:: from("United Kingdom"), + content: String::from("This is how we gonna die"), + }; + + println!("1 new article: {}",article.summarize()); +} |