-
Notifications
You must be signed in to change notification settings - Fork 0
/
trait_x.rs
132 lines (109 loc) · 2.55 KB
/
trait_x.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*
特性示例代码
*/
use std::fmt::{Debug, Display};
/// 自动派生特性
#[derive(Debug)]
struct Animal {
name: String,
}
pub fn test_auto_derive_trait() {
let animal = Animal {
name: String::from("Jack"),
};
println!(
"自动派生特性 Debug: animal {:?} with name = {}",
animal, animal.name
);
}
/// 定义特性
trait Fly {
fn fly(&self);
}
struct Bird {
name: String,
}
impl Fly for Bird {
fn fly(&self) {
println!("我是一只鸟 {},肯定会飞", self.name);
}
}
struct Fish {
name: String,
}
impl Fly for Fish {
fn fly(&self) {
println!("虽然我是一条鱼 {},但我会滑翔", self.name);
}
}
pub fn test_custom_fly_trait() {
let bird = Bird {
name: String::from("Jack"),
};
let fish = Fish {
name: String::from("Ann"),
};
bird.fly();
fish.fly();
}
/// 特性作为参数
/// fly_obj 是实现了 Fly 特性的结构的实例
fn call_fly(fly_obj: &impl Fly) {
fly_obj.fly();
}
/// call_fly(fly_obj: &impl Fly) 实际上是以下方法的语法糖
fn call_fly2<T: Fly>(fly_obj: &T) {
fly_obj.fly();
}
pub fn test_trait_as_parameter() {
let bird = Bird {
name: String::from("Jack"),
};
let fish = Fish {
name: String::from("Ann"),
};
call_fly(&bird);
call_fly(&fish);
call_fly2(&bird);
call_fly2(&fish);
}
/// 多重约束
/// 使用 + 定义多重约束
fn multiple_trait_bounds<T: Debug + Display>(obj: &T) {
println!("使用 + 定义多重约束 {}", obj);
println!("使用 + 定义多重约束 {:?}", obj);
}
struct Point {
x: f32,
y: f32,
}
impl Debug for Point {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Debug output => x = {}, y = {}", self.x, self.y)
}
}
impl Display for Point {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Display output => x = {}, y = {}", self.x, self.y)
}
}
pub fn test_multiple_trait_bounds() {
let s = "123";
multiple_trait_bounds(&s);
let point = Point { x: 1.2, y: 1.2 };
multiple_trait_bounds(&point);
}
/// where 约束
fn multiple_trait_bounds_where<T>(obj: &T)
where
T: Debug + Display,
{
println!("使用 + 和 where 定义多重约束 {}", obj);
println!("使用 + 和 where 定义多重约束 {:?}", obj);
}
pub fn test_multiple_trait_bounds_where() {
let s = "123";
multiple_trait_bounds_where(&s);
let point = Point { x: 1.2, y: 1.2 };
multiple_trait_bounds_where(&point);
}