(七)Rust结构体

本文最后更新于 2024年6月28日 下午

结构体和元组很相似,都能包含不同类型的变量,和元组不同的是,结构体对每一个变量独立命名,使用命名直接访问对应变量。

定义和初始化结构体

结构体定义

关键词struct用于定义并命名结构体。下面定义了一个结构体:

1
2
3
4
5
6
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}

其中,User为结构体名,花括号内一行称为字段,每一字段由变量类型和变量名组成并由逗号分隔。

结构体初始化

结构体的初始化参考如下代码:

1
2
3
4
5
6
7
8
9
10
fn main() {
let mut user1 = User {
active: true,
username: String::from("someusername123"),
email: String::from("someone@example.com"),
sign_in_count: 1,
};

user1.email = String::from("anotheremail@example.com");
}

和结构体定义很相似,通过将定义中的变量类型替换为相应初始化值,可以生成user1并且根据给定值初始化结构体。

可以使用.直接访问结构体中变量。

类元组结构体

在无需对结构体变量进行命名时,可以使用类似元组形式的结构体。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);

fn main() {
let black = Color(1, 2, 3);
let origin = Point(4, 5, 6);

let Color(x1,y1,z1) = black;
let x2 = origin.0;
let y2 = origin.1;
let z2 = origin.2;

println!("black({x1},{y1},{z1})");
println!("origin({x2},{y2},{z2})");
}

和元组一样,可以使用.或者模式匹配获取结构体中特定值。

结构体方法

结构体方法和函数类似:需要使用关键字fn和函数名定义,都能拥有参数和一个返回值;与函数不同的是,结构体方法第一个参数总是self且其指向调用方法的结构体。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct Rectangle {
width: u32,
height: u32,
}

impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}

fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};

println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
}

使用关键字implRectangle开启了一个代码块,在其中定义了area方法。area方法中传递的第一个参数&selfSelf: &self的缩写,Self代指当前代码块所在结构体类型。&self参数作为不可变引用无法对结构体内容进行修改;&mut self作为参数是可变引用,可以对结构体内容修改;self作为参数会转移所有权,被传入结构体将失效。

结构体相关函数

impl代码块下,不仅可以添加结构体方法,也可以添加相关函数。相关函数无需传入self,调用也无需结构体实例。之前代码中使用的String::from就是定义在String类型上的相关函数。

相关函数类似C++中的静态函数。

下面是一个生成正方形Rectangle的相关函数:

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
struct Rectangle {
width: u32,
height: u32,
}

impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}

impl Rectangle {
fn square(size: u32) -> Self {
Self {
width: size,
height: size,
}
}
}

fn main() {
let rect1 = Rectangle::square(100);

println!(
"Rectangle width:{} height:{}",rect1.width,rect1.height);

println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
}

在程序中,square被结构体Rectangle命名,使用::语法可以调用结构体中相关函数。

参考

Rust docs


(七)Rust结构体
https://www.happyallday.cn/Rust/RustLang_07_Structs/
作者
DevoutPrayer
发布于
2024年6月28日
更新于
2024年6月28日
许可协议