“ 模式有两种形式:可反驳的(refutable)和 不可反驳的(irrefutable)。”
let Some(x) = some_option_value;
$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
error[E0005]: refutable pattern in local binding: `None` not covered
--> 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.org/book/ch18-02-refutability.html
= note: the matched value is of type `Option<i32>`
help: you might want to use `if let` to ignore the variant that isn't matched
|
3 | if let Some(x) = some_option_value { /* */ }
|
error: aborting due to previous error
For more information about this error, try `rustc --explain E0005`.
error: could not compile `patterns`
To learn more, run the command again with --verbose.
if let Some(x) = some_option_value {
println!("{}", x);
}
if let x = 5 {
println!("{}", x);
};
尝试进行编译,Rust 会产生类似下面的告警(注意,不是错误):
warning: irrefutable `if let` pattern
--> src/main.rs:2:5
|
2 | / if let x = 5 {
3 | | println!("{}", x);
4 | | };
| |_____^
|
= note: `
= note: this pattern will always match, so the `if let` is useless
= help: consider replacing the `if let` with a `let`
warning: 1 warning emitted
Finished dev [unoptimized + debuginfo] target(s) in 0.39s
Running `target/debug/patterns`