
7

Rust -- 模式与匹配 - 北门吹雪
source link: https://www.cnblogs.com/2bjiujiu/p/17357415.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Rust -- 模式与匹配
用来匹配类型中的结构(数据的形状),结合 模式和match表达式 提供程序控制流的支配权
- 模式组成内容
- 解构的数组、枚举、结构体、元祖
流程:匹配值 --> 是否拥有正确的数据 --> 运行特定的代码
2. 使用模式的位置
- match分支:由match关键字、一个匹配的值和一个或多个分支构成
- 穷尽性:所有可能的值都必须考虑到
- _: 匹配所有情况,不绑定任何变量
enum Status {
// 其中对应的值通过 Status::OK as i32方式取出
OK = 200,
NotFound = 404,
Create = 201
}
fn main() {
let status = Status::OK;
match status {
// 将枚举
Status::OK => println!("{}", Status::OK as i32),
_ => println!()
}
}
- if let 语句
只关心一种情况的match分支的简写,可选的else在模式不匹配时执行,可以灵活搭配 else if 、else if let,搭配之间不需要关联性
- while let 条件循环
只要模式匹配就一直进行while循环
fn main() {
let mut stack = Vec::new();
// 推入数据
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
// 弹出数据
while let Some(v) = stack.pop() {
println!("value: {}", v)
}
}
- for循环
模式是for关键字直接跟随的值
fn main() {
let valuse = vec![1, 2, 3, 4, 5];
// 遍历vector,使用了模式对元祖进行解构
for (index, value) in valuse.iter().enumerate() {
println!("index: {}, value: {}", index, value)
}
}
- let 语句
将模式与表达式进行比较,并为任何找到的名称赋值
fn main() {
// 结构元祖
let (x, y, z) = (1, 2, 3);
println!("{}, {}, {}", z, y, x);
// 普通变量声明
let x = 5;
}
与let语句一致
fn function_pattern(&(x, y): &(i32, i32)) -> i32 {
x + y
}
fn main() {
let num = (1, 2);
let sum = function_pattern(&num);
println!("sum: {}", sum)
}
3. 模式分类
依据:是否会匹配可能失败
- 不可反驳: 能匹配任何传递的可能值
- let语句 for循环 函数
- 可反驳: 对某些可能存在的值进行匹配会失败
- if let、 while let、match分支
4. 模式语法
- 匹配字面量
fn main() {
let name = "beimen";
match name {
"beimen" => println!("beimen"),
"chuixue" => println!("chuixue"),
_ => println!("unknown")
}
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK