study_example/advance_feature/
advanced_trait.rs

1/*pub trait Iterator {
2    type Item;
3    fn next(&mut self) -> Option<Self::Item>;
4}
5
6struct Counter {}
7
8impl Iterator for Counter {
9    type Item = u32;
10    fn next(&mut self) -> Option<Self::Item> {}
11}
12
13pub trait Iterator_Generic<T> {
14    fn next(&mut self) -> Option<T>;
15}*/
16
17use std::ops::Add;
18
19#[derive(Debug)]
20struct Point {
21    x: i32,
22    y: i32,
23}
24
25impl Add for Point {
26    type Output = Point;
27
28    fn add(self, other: Point) -> Point {
29        Point {
30            x: self.x + other.x,
31            y: self.y + other.y,
32        }
33    }
34}
35
36// Newtype
37#[derive(Debug)]
38struct Millimeters(u32);
39struct Meters(u32);
40
41/*
42ADD定义如下
43trait Add<Rhs=Self> {
44    type Output;
45    fn add(self, rhs:Rhs) -> Self::Output;
46}
47*/
48
49impl Add<Meters> for Millimeters {
50    type Output = Millimeters;
51    fn add(self, other: Meters) -> Millimeters {
52        Millimeters(self.0 + (other.0 * 1000))
53    }
54}
55
56/// 运行结果为
57/// ```txt
58/// point: (Point { x: 0, y: 0 })
59/// millis: (Millimeters(4123))
60/// ```
61fn operator_overload() {
62    let point = Point { x: 1, y: -1 } + Point { x: -1, y: 1 };
63    println!("point: ({:?})", point);
64    let millis = Millimeters(123) + Meters(4);
65    println!("millis: ({:?})", millis);
66}
67
68trait Pilot {
69    fn fly(&self);
70}
71
72trait Wizard {
73    fn fly(&self);
74}
75
76struct Human;
77impl Pilot for Human {
78    fn fly(&self) {
79        println!("Pilot: this is your captain speking.");
80    }
81}
82
83impl Wizard for Human {
84    fn fly(&self) {
85        println!("Wizard: Up");
86    }
87}
88
89impl Human {
90    fn fly(&self) {
91        println!("*waving arms furiously*");
92    }
93}
94
95/// 运行结果为
96/// ```txt
97/// *waving arms furiously*
98/// Pilot: this is your captain speking.
99/// Wizard: Up
100/// ```
101fn same_fn_name_call() {
102    let person = Human;
103    person.fly();
104    // 对于没有第一个self参数的同名函数,需要显式指定实现的结构的类型如`<Dog as Animal>::baby_name()`,否则编译器会报错
105    Pilot::fly(&person);
106    Wizard::fly(&person);
107}
108
109use std::fmt;
110trait OutlinePrint: fmt::Display {
111    fn outline_print(&self) {
112        let output = self.to_string();
113        let len = output.len();
114        println!("{}", "*".repeat(len + 4));
115        println!("*{}*", " ".repeat(len + 2));
116        println!("* {} *", output);
117        println!("*{}*", " ".repeat(len + 2));
118        println!("{}", "*".repeat(len + 4));
119    }
120}
121
122// error[E0277]: `advanced_trait::Point` doesn't implement `std::fmt::Display`
123impl OutlinePrint for Point {}
124// fix如下
125impl fmt::Display for Point {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        write!(f, "({}, {})", self.x, self.y)
128    }
129}
130
131/// 运行结果如下
132/// ```txt
133/// ***********
134/// *         *
135/// * -23, 56 *
136/// *         *
137/// ***********
138/// ```
139fn super_trait_example() {
140    let point = Point { x: -23, y: 56 };
141    point.outline_print();
142}
143
144struct Wrapper(Vec<String>);
145impl fmt::Display for Wrapper {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        write!(f, "[{}]", self.0.join(", "))
148    }
149}
150
151/// 运行结果如下
152/// ```txt
153/// w: [Hello, Rust]
154/// ```
155fn newtype_pattern_external_trait() {
156    let w = Wrapper(vec![String::from("Hello"), String::from("Rust")]);
157    println!("w: {}", w);
158}
159
160pub fn advanced_trait_study() {
161    operator_overload();
162    same_fn_name_call();
163    super_trait_example();
164    newtype_pattern_external_trait();
165}