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
//1.trait定义与其他类型共享的功能,类似其他语言的接口
//(1)可以通过trait以抽象的方式定义共享的行为
// (2) 可以使用trait bounds指定泛型是任何拥有特定行为的类型
//2. 定义trait
//3. 实现trait
//4. 默认实现: 可以在定义trait的时候提供默认的行为,trait的类型可以使用默认的行为.
//5. trait作为参数

//2.
pub trait GetInformation {
fn get_name(&self) -> &String;
fn get_age(&self) -> u32;
}
trait SchoolName {
fn get_school_name(&self) -> String {//默认实现
String::from("HongXing School")//避免悬垂引用
}
}
//3.
pub struct Student {
pub name: String,
pub age: u32,
}

impl SchoolName for Student {

}
impl GetInformation for Student {
fn get_name (&self) -> &String {
&self.name
}
fn get_age(&self) -> u32 {//这里因为u32实现了copy trait类型,所以返回本体
self.age
}
}
pub struct Teacher {
pub name:String,
pub age: u32,
pub subject: String,
}
impl GetInformation for Teacher {
fn get_name (&self) -> &String {
&self.name
}
fn get_age(&self) -> u32 {//这里因为u32实现了copy trait类型,所以返回本体
self.age
}
}
impl SchoolName for Teacher {
fn get_school_name(&self) -> String {
String::from("Guangmingschool")//修改默认实现
}
}
//4.
//5.
fn print_information(item: impl GetInformation) {
//这里只关心是否实现impl trait,然后调用item实现的方法即可
println!("name = {}",item.get_name());
println!("age = {}",item.get_age());

}
fn main() {
let s = Student{name:"xiaoming".to_string(),age:10};
let t = Teacher{name:"xiaohu".to_string(),age:30,subject: "math".to_string};
println!("student, name = {},age = {}",s.get_name(),s.get_age());
println!("student, name = {},age = {}",t.get_name(),t.get_age());

let s_school_name = s.get_school_name();
println!("student school name = {}",s_school_name);
let t_school_name = t.get_school_name();
print_information(s);
print_information(t);
}