-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstruct.rs
More file actions
58 lines (50 loc) · 1.31 KB
/
struct.rs
File metadata and controls
58 lines (50 loc) · 1.31 KB
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
// 基本的结构体
struct Person {
name: String,
age: u32,
address: String,
}
impl Person {
// 构造函数
fn new(name: &str, age: u32, address: &str) -> Person {
Person {
name: name.to_string(),
age,
address: address.to_string(),
}
}
// 方法
fn introduce(&self) {
println!("Hi, I am {}, {} years old, from {}.", self.name, self.age, self.address);
}
}
// 继承示例:使用组合模拟继承
struct Employee {
person: Person,
position: String,
}
impl Employee {
// 构造函数
fn new(name: &str, age: u32, address: &str, position: &str) -> Employee {
Employee {
person: Person::new(name, age, address),
position: position.to_string(),
}
}
// 方法
fn introduce(&self) {
println!("I am {}, a {} at the company, living in {}.", self.person.name, self.position, self.person.address);
}
}
fn main() {
let p1 = Person::new("Alice", 30, "123 Main St");
p1.introduce();
let e1 = Employee::new("Bob", 28, "456 Elm St", "Software Developer");
e1.introduce(); // 覆盖了Person的introduce方法
}
/*
jarry@MacBook-Pro struct % rustc struct.rs
jarry@MacBook-Pro struct % ./struct
Hi, I am Alice, 30 years old, from 123 Main St.
I am Bob, a Software Developer at the company, living in 456 Elm St.
*/