Rust基础(4)-结构体和方法

结构体和方法

结构体

  1. 定义结构体
  2. 创建结构体实例
  3. 修改结构体字段
  4. 参数名字和字段名字同名的简写方法
  5. 从其它结构体创建实例
  6. 元组结构体
  7. 没有任何字段的类单元结构体
  8. 打印结构体
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
fn main() {
//1. 定义结构体
#[derive(Debug)]
struct User {
name: String,
count: String,
nonce: u64,
active: bool,
}
//2. 创建结构体实例
let xiaoming = User {
name: String::from("xiaoming"),
count: String::from("80001000"),
nonce: 10000,
active: true,
};
//3. 修改结构体字段
let mut xiaohuang = User {
name: String::from("xiaohuang"),
count: String::from("80001000"),
nonce: 10000,
active: true,
};
xiaohuang.nonce = 20000;
//4. 参数名字和字段名字同名的简写方法
let name = String::from("xiaoxiao");
let count = String::from("89077777");
let active = false;
let nonce = 30000;
/*let user1 = User{ //太繁琐
name: name,
count:count,
nonce:nonce,
active:active,
};*/
let user1 = User { //简写
name,
count,
nonce,
active,
};
//5. 从其它结构体创建实例
let user2 = User {
..user1 //user1被移动,之后不能再使用 user1
};
println!("name = {}", user2.name);
let user3 = User {
name: String::from("user3"),
..user2
};
println!("name = {}", user3.name);
//6. 元组结构体
//6.1 字段没有名字
//6.2 圆括号
struct Point(i32, i32);
let a = Point(10, 20);
let b = Point(30, 11);
println!("a.x = {},a.y = {}", a.0, a.1);
//7. 没有任何字段的类单元结构体
struct A {}
//8. 打印结构体
//结构体上方加上:#[derive(Debug)]
println!("xiaoming = {:?}", xiaoming);
//可自动换行
println!("xiaoming = {:#?}", xiaoming);
}

方法

  1. 方法可以写在不同的impl语句块
  2. 可以对外静态方法,需要通过:Dog::show()方式调用
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
#[derive(Debug)]
struct Dog {
name: String,
weight: f32,
height: f32,
}

impl Dog {
fn get_name(&self) -> &str {
&(self.name[..])
}
fn get_weight(&self) -> f32 {
self.weight
}
//此方法没有传入self,类似对外的静态方法,需要用 Dog::show()调用
fn show(){
println!("oh oh oh");
}
}
impl Dog{
fn get_height(&self) -> f32 {
self.height
}
}

fn main() {
let dog = Dog {
name: String::from("wangcai"),
weight: 100.0,
height: 70.5,
};
println!("dog = {:#?}",dog);
println!("name = {}",dog.get_name());
println!("weight = {}",dog.get_weight());
Dog::show();
}

总结

已编辑完毕

参考

[1] Rust 程序设计语言

  • Copyrights © 2017-2023 Jason
  • Visitors: | Views:

谢谢打赏~

微信