提交 9608d4cb 编写于 作者: jackymao.com's avatar jackymao.com

add match excercise

上级 197a9c7d
......@@ -2,5 +2,7 @@
"node_id": "rust-73665fa29a214d2bb55ead28656063cb",
"keywords": [],
"children": [],
"export": []
"export": [
"match.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"author": "jacky_rust",
"source": "match.md",
"notebook_enable": false
}
\ No newline at end of file
# match 表达式
Rust 的 match 表达式类似 C 语言的 switch 语句,但比之更强大。
```rust
fn main() {
let x = 42;
match x {
0 => { println!("zero"); }
1 => { println!("one"); }
2 => { println!("two"); }
3..=41 => { println!("between 3 and 41 (ends included)"); }
42 => { println!("The answer"); }
n @ 43..=99
=> { println!("Hint: the answer is smaller than {}", n); }
_ => { println!("out of the range"); }
}
}
```
match 还可以直接使用多值模式匹配
```rust
fn main() {
let p = (2, 4);
match p {
(0, 0) => { println!("Bingo! Origin of coordinates."); }
(0, _y) => { println!("On the X axis."); }
(_x, 0) => { println!("On the Y axis."); }
_ => { println!("Not on the axises"); }
}
}
```
match 还可以将返回值作为右值给变量赋值。另外要注意 match 的每个分支返回的数据类型要相同。
下列选项中,能正确打印一个不在 X 或 Y 轴上的点的 x, y 坐标的是:
## 答案
```rust
fn main() {
let p = (2, 4);
let result = match p {
(0, 0) => { (0, 0) }
(0, _y) => { (0, 0) }
(_x, 0) => { (0, 0) }
(x, y) => { (x, y) }
};
println!("x: {}, y: {}", result.0, result.1);
}
```
## 选项
### let 赋值语句不要忘记分号
```rust
fn main() {
let p = (2, 4);
let result = match p {
(0, 0) => { (0, 0) }
(0, _y) => { (0, 0) }
(_x, 0) => { (0, 0) }
(x, y) => { (x, y) }
}
println!("x: {}, y: {}", result.0, result.1);
}
```
### match 分支要返回同类似的值
```rust
fn main() {
let p = (2, 4);
let result = match p {
(0, 0) => { println!("Bingo! Origin of coordinates."); }
(0, _y) => { println!("On the X axis."); }
(_x, 0) => { println!("On the Y axis."); }
(x, y) => { (x, y) }
};
println!("x: {}, y: {}", x, y);
}
```
### match 分支要用逗号分隔,或用花括号包括语句以自动返回 () 值
```rust
fn main() {
let p = (2, 4);
match p {
(0, 0) => println!("Bingo! Origin of coordinates.");
(0, _y) => println!("On the X axis.");
(_x, 0) => println!("On the Y axis.");
(x, y) => println!("x: {}, y: {}", x, y);
}
}
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册