gw_rust_programming_tutorial/chapter_10/
test_traits.rs1pub trait Summary {
3 fn summarize(&self) -> String{
4 String::from("(Read more...)")
5 }
6}
7
8pub struct NewsArticle {
10 pub headline: String,
11 pub location: String,
12 pub author: String,
13 pub content: String,
14}
15
16impl Summary for NewsArticle {
18 fn summarize(&self) -> String {
19 format!("{}, by {} ({})", self.headline, self.author, self.location)
20 }
21}
22
23pub struct Tweet {
24 pub username: String,
25 pub content: String,
26 pub reply: bool,
27 pub retweet: bool,
28}
29
30impl Summary for Tweet {
32 fn summarize(&self) -> String {
33 format!("{}: {}", self.username, self.content)
34 }
35}
36pub fn test_trait_fn()
37{
38 let tweet = Tweet {
39 username: String::from("horse_ebooks"),
40 content: String::from("of course, as you probably already know, people"),
41 reply: false,
42 retweet: false,
43 };
44
45 println!("1 new tweet: {}", tweet.summarize());
47}
48
49use std::fmt::Display;
50
51struct Pair<T> {
52 x: T,
53 y: T,
54}
55
56impl<T> Pair<T> {
57 fn new(x: T, y: T) -> Self {
58 Self {
59 x,
60 y,
61 }
62 }
63}
64
65impl<T: Display + PartialOrd> Pair<T> {
66 fn cmp_display(&self) {
67 if self.x >= self.y {
68 println!("The largest member is x = {}", self.x);
69 } else {
70 println!("The largest member is y = {}", self.y);
71 }
72 }
73}
74
75