aolifu_rust/
trait_mod.rs

1use std::arch::x86_64::_bittest;
2use std::fmt::{Debug, Display};
3use std::iter::Sum;
4
5pub trait Summary {
6    fn summarize(&self) -> String;
7
8    fn summarize_author(&self) -> String {
9        format!("Read more form {}", self.summarize())
10    }
11}
12
13pub struct NewsArticle {
14    pub headline: String,
15    pub location: String,
16    pub author: String,
17    pub content: String,
18}
19
20impl Summary for NewsArticle {
21    fn summarize(&self) -> String {
22        format!("{}, by {} ({})", self.headline, self.author, self.content)
23    }
24}
25
26pub struct Tweet {
27    pub username: String,
28    pub content: String,
29    pub reply: bool,
30    pub retweet: bool,
31}
32
33impl Summary for Tweet {
34    fn summarize(&self) -> String {
35        format!("{}: {}", self.username, self.content)
36    }
37}
38
39pub fn send_tweet() {
40    let tweet = Tweet{
41        username: String::from("Oliver"),
42        content: String::from("this is a good day"),
43        reply: true,
44        retweet: false,
45    };
46    let summary = tweet.summarize();
47    println!("summary is {}", summary);
48}
49
50pub fn notify(item: impl Summary) {
51    println!("breaking news ! {}", item.summarize())
52}
53
54pub fn notify_two<T: Summary>(item: T) {
55    println!("breaking news! {}", item.summarize())
56}
57
58pub fn notify_three<T: Summary + Display>(item: T) {
59    println!("breaking news! {}", item.summarize())
60}
61
62pub fn notify_four(item: impl Summary + Display) {
63    println!("breaking news! {}", item.summarize())
64}
65
66pub fn notify_five<T: Summary + Display, U: Clone + Debug>(a: T, b: U) -> String {
67    format!("breaking news ! {}", a.summarize())
68}
69
70pub fn notify_six<T, U>(a: T, b: U) -> String
71    where T: Summary + Display,
72        U: Clone + Debug,
73{
74    format!("breaking news! {}", a.summarize())
75}
76
77pub fn trait_return_notify() -> impl Summary {
78    NewsArticle{
79        headline: String::from("headline_test"),
80        location: String::from("location_test"),
81        author: String::from("author_test"),
82        content: String::from("content_test"),
83    }
84}
85
86struct Pair<T> {
87    x: T,
88    y: T,
89}
90
91// trait bound without condition
92impl<T> Pair<T>{
93    fn New(x: T, y: T) -> Self {
94        Pair{
95            x, y,
96
97        }
98    }
99}
100
101// trait bound with condition
102impl <T: Display + PartialOrd> Pair<T> {
103    fn cmp_display(&self) {
104        if self.x > self.y {
105            println!("The largest num is x:{}", self.x);
106        } else {
107            println!("The largest num is y:{}", self.y);
108        }
109    }
110}