study_rust_example/generic_traits_lifetime/
traits_study.rs

1use std::fmt::Display;
2
3struct Pair<T> {
4    x: T,
5    y: T,
6}
7impl<T> Pair<T> {
8    fn new(x: T, y: T) -> Self {
9        Self { x, y }
10    }
11}
12impl<T: Display + PartialOrd> Pair<T> {
13    fn cmp_display(&self) {
14        if self.x >= self.y {
15            println!("The largest member is x = {}", self.x);
16        } else {
17            println!("The largest member is y = {}", self.y);
18        }
19    }
20}
21trait Summary {
22    fn summarize(&self) -> String;
23}
24
25struct Tweet {
26    pub content: String,
27    pub autor: String,
28}
29
30impl Summary for Tweet {
31    fn summarize(&self) -> String {
32        format!("{} by {}", self.autor, self.content)
33    }
34}
35
36struct Article {
37    pub headline: String,
38    pub location: String,
39    pub author: String,
40}
41
42impl Summary for Article {
43    fn summarize(&self) -> String {
44        format!(
45            "{} by {}, locate: {}",
46            self.headline, self.author, self.location
47        )
48    }
49}
50
51fn notify(item: &impl Summary) {
52    println!("Breaking news: {}", item.summarize());
53}
54
55pub fn traits_usage_study() {
56    let article = Article {
57        headline: String::from("article headline"),
58        location: String::from("canada"),
59        author: String::from("clare"),
60    };
61    println!("article summary {}", article.summarize());
62    notify(&article);
63}