共计 1762 个字符,预计需要花费 5 分钟才能阅读完成。
if let 语法使您能够将 if 和 let 组合成一种不太简短的形式来解决与一种模式匹配的值,而疏忽其余模式。例如:该程序与 Option <u8> 值匹配,但仅想在值为 3 时执行代码:
fn main() {let some_u8_value = Some(0u8);
match some_u8_value {Some(3) => println!("three"),
_ => (println!("啥也不是")),
}
}
咱们想对 Some(3) 匹配做点什么,但对其余 Some <u8> 值或 None 值什么都不做。为了满足 match 表达式,咱们只须要解决一个变体就增加_ =>(),然而须要增加的许多样板代码。
相同,咱们能够应用 if let 以更短的形式编写此代码并实现完全一致的匹配成果:
fn main() {let some_u8_value = Some(8u8);
if let Some(3) = some_u8_value {println!("three");
}
if let Some(8) = some_u8_value {println!("匹配到了");
}
}
D:\learn\cargo_learn>cargo run
Compiling cargo_learn v0.1.0 (D:\learn\cargo_learn)
Finished dev [unoptimized + debuginfo] target(s) in 0.27s
Running `target\debug\cargo_learn.exe`
匹配到了
相应的如果咱们想要失去一个确切的后果,比方如果没有匹配到咱们须要的那个咱们心愿有返回后果,那么此时能够应用 else
:
#[derive(Debug)]
enum UsState {
Alabama,
Alaska,
}
enum Coin {
Penny,
Quarter(UsState),
}
fn main() {
let coin = Coin::Penny;
let mut count = 0;
if let Coin::Quarter(state) = coin {println!("State quarter from {:?}!", state);
} else {
count += 1;
println!("没有匹配到任何后果,count 将主动 +1!!!")
}
}
D:\learn\cargo_learn>cargo run
Compiling cargo_learn v0.1.0 (D:\learn\cargo_learn)
warning: variable `count` is assigned to, but never used
--> src\main.rs:14:9
|
14 | let mut count = 0;
| ^^^^^^^^^
|
= note: `#[warn(unused_variables)]` on by default
= note: consider using `_count` instead
warning: value assigned to `count` is never read
--> src\main.rs:18:9
|
18 | count += 1;
| ^^^^^
|
= note: `#[warn(unused_assignments)]` on by default
= help: maybe it is overwritten before being read?
warning: variant is never constructed: `Alabama`
--> src\main.rs:3:5
|
3 | Alabama,
| ^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: variant is never constructed: `Alaska`
--> src\main.rs:4:5
|
4 | Alaska,
| ^^^^^^
warning: variant is never constructed: `Quarter`
--> src\main.rs:9:5
|
9 | Quarter(UsState),
| ^^^^^^^^^^^^^^^^
warning: 5 warnings emitted
Finished dev [unoptimized + debuginfo] target(s) in 0.51s
Running `target\debug\cargo_learn.exe`
没有匹配到任何后果,count 将主动 +1!!!
正文完