Rust学习笔记_06——控制流(2)
Rust学习笔记_07——枚举和范围
Rust学习笔记_08——String
Matching Values
1. 介绍
Rust的模式匹配主要通过match
表达式来实现,它可以与多种模式进行匹配,并根据匹配到的模式执行相应的代码块。在模式匹配中,匹配值(Matching Values)是指match
表达式中被检查的变量或表达式的值。
let x = 1;
match x {
pattern1 => {
// 当x匹配pattern1时执行的代码
}
pattern2 => {
// 当x匹配pattern2时执行的代码
}
// 可以有更多的模式
_ => {
// 当x不匹配任何前面的模式时执行的代码(也称为"通配符"模式)
}
}
2. 匹配字面量
let number = 1;
match number {
1 => println!("One"),
2 => println!("Two"),
3 => println!("Three"),
_ => println!("Something else"),
}
3. 匹配枚举
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
let msg = Message::ChangeColor(255, 0, 0);
match msg {
Message::Quit => println!("Quit the game"),
Message::Move { x, y } => println!("Move to position ({}, {})", x, y),
Message::Write(text) => println!("Write: {}", text),
Message::ChangeColor(r, g, b) => println!("Change color to RGB({}, {}, {})", r, g, b),
}
4. 匹配范围
let number = 50;
match number {
0...9 => println!("0-9"),
10...19 => println!("10-19"),
20...49 => println!("20-49"),
50...99 => println!("50-99"),
_ => println!("100+"),
}
5. 匹配守卫
let number = 10;
match number {
n if n < 20 => println!("less than 20"),
n if n >= 20 && n < 100 => println!("between 20 and 99"),
_ => println!("100 or greater"),
}
6. 匹配绑定值
let point = (3, 4);
match point {
(0, 0) => println!("Origin"),
(x, 0) => println!("On the x-axis at {}", x),
(0, y) => println!("On the y-axis at {}", y),
(x, y) => println!("At position ({}, {})", x, y),
}