study_example/advance_feature/
advanced_trait.rs1use 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#[derive(Debug)]
38struct Millimeters(u32);
39struct Meters(u32);
40
41impl 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
56fn 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
95fn same_fn_name_call() {
102 let person = Human;
103 person.fly();
104 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
122impl OutlinePrint for Point {}
124impl fmt::Display for Point {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 write!(f, "({}, {})", self.x, self.y)
128 }
129}
130
131fn 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
151fn 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}