1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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<T: Summary>(item: &T) {
println!("Breaking news! {}", item.summarize());
}
// statements below are equivalent
// pub fn nofity(item1: &impl Summary, item2: Summary) {}
// pub fn nofity<T: Summary>(item1: &T, item2: &T) {}
// use std::fmt::Display;
// multiple bound
// pub fn notify(item: &(impl Summary + Display)) {}
// or
// pub fn notify<T: Summary + Display>(item: &T) {}
// where clause
// pub fn notify<T>(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,
}
}
|