Skip to content

Commit f120e8d

Browse files
Using traits to defing common behavior
1 parent 4f770e8 commit f120e8d

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

rustlang_book/traits/Cargo.toml

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[package]
2+
name = "traits"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]

rustlang_book/traits/src/main.rs

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
pub trait Summary {
2+
fn summarize(&self) -> String {
3+
return String::from("Read more...");
4+
}
5+
}
6+
7+
pub struct NewsArticle {
8+
pub headline: String,
9+
pub location: String,
10+
pub author: String,
11+
pub content: String,
12+
}
13+
14+
impl Summary for NewsArticle {}
15+
16+
pub struct Tweet {
17+
pub username: String,
18+
pub content: String,
19+
pub reply: bool,
20+
pub retweet: bool,
21+
}
22+
23+
impl Summary for Tweet {
24+
fn summarize(&self) -> String {
25+
return format!("{}: {}", self.username, self.content);
26+
}
27+
}
28+
fn main() {
29+
let tweet = Tweet {
30+
username: String::from("just_a_kid_with_a_dream"),
31+
content: String::from("You feel like home"),
32+
reply: false,
33+
retweet: false,
34+
};
35+
36+
println!("1 new tweet: {}", tweet.summarize());
37+
38+
let article = NewsArticle {
39+
headline: String::from("Penguins win the Stanley Cup Championship!"),
40+
location: String::from("Pittsburgh, PA, USA"),
41+
author: String::from("Iceburgh"),
42+
content: String::from(
43+
"The Pittsburgh Penguins once again are the best \
44+
hockey team in the NHL.",
45+
),
46+
};
47+
48+
println!("New article available! {}", article.summarize());
49+
}

0 commit comments

Comments
 (0)