From 58d17bab39ca098adbf94699d6adf2876a8192f6 Mon Sep 17 00:00:00 2001 From: doraemon Date: Fri, 21 Apr 2023 00:09:29 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=B8=80=E4=B8=AAmatch?= =?UTF-8?q?=E7=9A=84=E4=BE=8B=E5=AD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在学习章节 `2.11.2. 返回值 Result 和?` 时遇到一个新的match用法,之前没有提到过,所以在这里加上。 https://course.rs/basic/result-error/result.html#%E5%AF%B9%E8%BF%94%E5%9B%9E%E7%9A%84%E9%94%99%E8%AF%AF%E8%BF%9B%E8%A1%8C%E5%A4%84%E7%90%86 --- src/basic/match-pattern/match-if-let.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/basic/match-pattern/match-if-let.md b/src/basic/match-pattern/match-if-let.md index 3f30909a..842080ef 100644 --- a/src/basic/match-pattern/match-if-let.md +++ b/src/basic/match-pattern/match-if-let.md @@ -255,6 +255,26 @@ match some_u8_value { 通过将 `_` 其放置于其他分支后,`_` 将会匹配所有遗漏的值。`()` 表示返回**单元类型**与所有分支返回值的类型相同,所以当匹配到 `_` 后,什么也不会发生。 +除了`_`通配符,用一个变量来承载其他情况也是可以的。 + +```rust +#[derive(Debug)] +enum Direction { + East, + West, + North, + South, +} + +fn main() { + let dire = Direction::South; + match dire { + Direction::East => println!("East"), + other => println!("other direction: {:?}", other), + }; +} +``` + 然而,在某些场景下,我们其实只关心**某一个值是否存在**,此时 `match` 就显得过于啰嗦。 ## `if let` 匹配