rust match
时间: 2023-10-10 10:11:59 浏览: 46
Rust's match expression is a powerful control flow construct that allows you to match a value against a set of patterns and execute code based on the matched pattern. The match expression consists of a match keyword, followed by an expression to match against, and a set of arms that define the patterns to match against and the code to execute if a pattern is matched.
Here is an example of using match to handle different types of values:
```
fn main() {
let x = 5;
match x {
1 => println!("One"),
2 | 3 => println!("Two or Three"),
4...7 => println!("Between Four and Seven"),
_ => println!("Something else"),
}
}
```
In this example, we match against the value of `x`. The first arm matches if `x` is equal to 1 and prints "One". The second arm matches if `x` is equal to 2 or 3 and prints "Two or Three". The third arm matches if `x` is between 4 and 7 (inclusive) and prints "Between Four and Seven". The last arm matches anything else and prints "Something else". The `_` is a catch-all pattern that matches anything that hasn't already been matched.
Match expressions can also be used with enums to match against the different variants:
```
enum Color {
Red,
Green,
Blue,
}
fn main() {
let color = Color::Green;
match color {
Color::Red => println!("Red"),
Color::Green => println!("Green"),
Color::Blue => println!("Blue"),
}
}
```
In this example, we match against the `color` enum. The first arm matches if the variant is `Red` and prints "Red". The second arm matches if the variant is `Green` and prints "Green". The third arm matches if the variant is `Blue` and prints "Blue". Since we have covered all possible variants, we don't need a catch-all pattern.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)