1. 概述
Rust 中的 match 是一个非常强大的流程控制操作符,它允许你对一个值进行模式匹配,然后根据匹配的模式执行相应的代码。
match表达式会依次判断模式列表,如果符合条件,将执行对应的代码。如果包含多行代码,可以使用{}。
2. 模式匹配介绍
下面介绍下常见的匹配方式
Rust 中的模式匹配非常强大,可以用于多种复杂的数据结构。以下是一些常见的匹配模式:
2.1 字面值模式
最简单的模式,就是直接匹配字面值。
```rust
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
_ => println!("anything"),
}
```
2.2 变量模式
匹配任何值,并将值绑定到变量中。
```rust
let x = 1;
match x {
e => println!("The number is: {}", e),
}
```
2.3 通配模式
使用 _ 符号,匹配任何值,但不绑定值。
```rust
let x = 1;
match x {
1 => println!("one"),
_ => println!("not one"),
}
```
2.4 范围模式
匹配一个范围内的值。
```rust
let x = 5;
match x {
1 ..= 5 => println!("one through five"),
_ => println!("anything"),
}
```
2.5 引用模式
匹配引用,并获取其引用的值。
```rust
let x = 5;
let y = &x;
match y {
&val => println!("Got a value: {}", val),
}
```
2.6 结构体模式
匹配结构体的值。
```rust
struct Point {
x: i32,
y: i32,
}
let point = Point { x: 0, y: 7 };
match point {
Point { x, y: 0 } => println!("On the x axis at {}", x),
Point { x: 0, y } => println!("On the y axis at {}", y),
Point { x, y } => println!("On neither axis: ({}, {})", x, y),
}
```
2.7 元组模式
匹配元组的值。
```rust
let pair = (0, -2);
match pair {
(0, y) => println!("First is `0` and `y` is `{:?}`", y),
(x, 0) => println!("`x` is `{:?}` and last is `0`", x),
_ => println!("It doesn't matter what they are"),
}
```
2.8 枚举模式
匹配枚举的值。
```rust
enum Color {
Red,
Blue,
Green,
RGB(u32, u32, u32),
}
let color = Color::Blue;
match color {
Color::Red => println!("Red"),
Color::Blue => println!("Blue"),
Color::Green => println!("Green"),
Color::RGB(r, g, b) => println!("r: {}, g: {}, b: {}", r, g, b),
}
```
2.9 数组和切片模式
匹配数组和切片的值。
```rust
let arr = [1, 2, 3];
match arr {
[1, _, _] => "starts with one",
[a, b, c] => "starts with something else",
_ => "not interesting",
}
```
2.10 守卫模式
在匹配模式后添加一个 if 表达式,这个表达式称为守卫。
let pair = (2, -2);
match pair {
(x, y) if x == y => println!("These are twins"),
(x, y) if x + y == 0 => println!("Antimatter, kaboom!"),
(x, _) if x % 2 == 1 => println!("The first one is odd"),
_ => println!("No correlation..."),
}
在上述代码中,if x == y、if x + y == 0 和 if x % 2 == 1 就是守卫。
2.11 @ 捕获模式
使用 @ 符号可以在创建一个模式同时给它赋一个变量名。
let some_value = 5;
match some_value {
e @ 1..=5 => println!("got a range element {}", e),
_ => (),
}
在上述代码中,e @ 1...5 就是 @ 捕获模式,它会匹配所有在 1 到 5 之间的数,并将匹配的数赋值给 e。
2.12 ? 操作符模式
在 Option 或 Result 类型中,? 操作符可以用来匹配并解构 Some 或 Ok 的值。
let optional = Some(7);
match optional {
Some(i) => println!("This is a really long string and `{:?}`", i),
_ => {},
}
在上述代码中,Some(i) 就是使用了 ? 操作符的模式,它会匹配所有的 Some,并将 Some 中的值赋值给 i。
2.13 ref 模式
用于获取引用的值。
let x = 5;
match x {
ref r => println!("Got a reference to {}", r),
}
在上述代码中,ref r 是 ref 模式,它会匹配任何值,并将匹配的值的引用赋值给 r。
2.14 mut 模式
用于匹配可变引用。
let mut x = 5;
match x {
ref mut mr => println!("Got a mutable reference to {}", mr),
}
在上述代码中,ref mut mr 是 mut 模式,它会匹配任何值,并将匹配的值的可变引用赋值给 mr。
这些都是 Rust 中常见的模式匹配用法,它们可以灵活组合,满足各种复杂的匹配需求。
3. 匹配Option枚举
macth可以匹配枚举值,如下示例代码
fn main() {
let five = Some(5);
let six = puls_one(five);
let none = puls_one(None);
}
fn puls_one(x :Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1)
}
}
4. 注意
match必须穷枚举所有可能的值,特别是 Option类型的数据,如果不想穷枚举所有可能的值,需要使用_来代替,如下示例代码
fn main() {
let v = 0u8;
match v {
1 => println!("one"),
3 => println!("three"),
5 => println!("five"),
7 => println!("seven"),
_ => (),
}
}