可反驳性:模式可能无法匹配的情况
模式有两种形式:可反驳的和不可反驳的。对于任何可能传递的值都会匹配的模式是不可反驳的。例如,语句 let x = 5;
中的 x
,因为 x
匹配任何内容,因此不可能匹配失败。对于某些可能的值可能匹配失败的模式是可反驳的。这里有一些例子
- 在表达式
if let Some(x) = a_value
中,Some(x)
是可反驳的。如果a_value
变量中的值是None
而不是Some
,则Some(x)
模式将不会匹配。 - 在表达式
if let &[x, ..] = a_slice
中,&[x, ..]
是可反驳的。如果a_slice
变量中的值有零个元素,则&[x, ..]
模式将不会匹配。
函数参数、let
语句和 for
循环只能接受不可反驳的模式,因为当值不匹配时,程序无法执行任何有意义的操作。if let
和 while let
表达式接受可反驳和不可反驳的模式,但编译器会警告不要使用不可反驳的模式,因为根据定义,它们旨在处理可能的失败:条件语句的功能在于其根据成功或失败执行不同操作的能力。
一般来说,您不必担心可反驳和不可反驳模式之间的区别;但是,您确实需要熟悉可反驳性的概念,以便在错误消息中看到它时能够做出响应。在这些情况下,您需要根据代码的预期行为,更改模式或使用模式的构造。
让我们看一个例子,当我们尝试在 Rust 要求不可反驳模式的地方使用可反驳模式,反之亦然时会发生什么。列表 18-8 显示了一个 let
语句,但对于我们指定的模式 Some(x)
,这是一个可反驳的模式。正如您可能预料到的,这段代码将无法编译。
fn main() {
let some_option_value: Option<i32> = None;
let Some(x) = some_option_value;
}
列表 18-8:尝试在 let
中使用可反驳模式
如果 some_option_value
是一个 None
值,它将无法匹配模式 Some(x)
,这意味着该模式是可反驳的。但是,let
语句只能接受不可反驳的模式,因为代码无法对 None
值执行任何有效的操作。在编译时,Rust 会抱怨我们试图在需要不可反驳模式的地方使用可反驳模式
$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
error[E0005]: refutable pattern in local binding
--> src/main.rs:3:9
|
3 | let Some(x) = some_option_value;
| ^^^^^^^ pattern `None` not covered
|
= note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant
= note: for more information, visit https://doc.rust-lang.net.cn/book/ch18-02-refutability.html
= note: the matched value is of type `Option<i32>`
help: you might want to use `let else` to handle the variant that isn't matched
|
3 | let Some(x) = some_option_value else { todo!() };
| ++++++++++++++++
For more information about this error, try `rustc --explain E0005`.
error: could not compile `patterns` (bin "patterns") due to 1 previous error
因为我们没有(也无法!)用模式 Some(x)
覆盖每个有效值,所以 Rust 理所当然地产生了一个编译器错误。
如果我们在需要不可反驳模式的地方使用了可反驳模式,我们可以通过更改使用该模式的代码来修复它:我们可以使用 if let
而不是 let
。然后,如果模式不匹配,代码将只跳过花括号中的代码,使其能够继续有效地执行。列表 18-9 展示了如何修复列表 18-8 中的代码。
fn main() { let some_option_value: Option<i32> = None; if let Some(x) = some_option_value { println!("{x}"); } }
列表 18-9:使用 if let
和带有可反驳模式的代码块而不是 let
我们给了代码一个退路!这段代码现在完全有效。但是,如果我们给 if let
一个不可反驳的模式(一个总是会匹配的模式),例如 x
,如列表 18-10 所示,编译器会发出警告。
fn main() { if let x = 5 { println!("{x}"); }; }
列表 18-10:尝试在 if let
中使用不可反驳模式
Rust 抱怨说在 if let
中使用不可反驳模式没有意义
$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
warning: irrefutable `if let` pattern
--> src/main.rs:2:8
|
2 | if let x = 5 {
| ^^^^^^^^^
|
= note: this pattern will always match, so the `if let` is useless
= help: consider replacing the `if let` with a `let`
= note: `#[warn(irrefutable_let_patterns)]` on by default
warning: `patterns` (bin "patterns") generated 1 warning
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.39s
Running `target/debug/patterns`
5
因此,match
分支必须使用可反驳模式,但最后一个分支除外,最后一个分支应该使用不可反驳模式匹配任何剩余值。Rust 允许我们在只有一个分支的 match
中使用不可反驳模式,但这语法不是特别有用,可以用更简单的 let
语句代替。
现在您已经知道在何处使用模式以及可反驳模式和不可反驳模式之间的区别,让我们介绍一下可以用来创建模式的所有语法。