gpt4 book ai didi

rust - Rust 中的 match 和 if-let 之间的主要区别是什么?

转载 作者:行者123 更新时间:2023-12-04 14:43:38 24 4
gpt4 key购买 nike

在学习控制流时,我很少感到困惑。我不明白 if-let 之间的区别和 match .

fn main() {
let some_u8_value = Some(8u8);
// println!(" {} ", some_u8_value);
if let Some(value) = some_u8_value {
println!(" {} ", value);
} else {
println!("not a num");
}

match some_u8_value {
Some(value) => println!(" {} ", value),
None => println!("not a num"),
}
}
为什么我们需要 if-let ?

最佳答案

Why do we need if-let?


我们不需要它,这是一个方便的功能。每 RFC 160其中介绍了它:

[if let] allows for refutable pattern matching without the syntactic and semantic overhead of a full match, and without the corresponding extra rightward drift.



The idiomatic solution today for testing and unwrapping an Option looks like

match optVal {
Some(x) => {
doSomethingWith(x);
}
None => {}
}

This is unnecessarily verbose, with the None => {} (or _ => {}) case being required, and introduces unnecessary rightward drift (this introduces two levels of indentation where a normal conditional would introduce one).

[explanation of the issues with using a simple if with is_some and unwrap]

The if let construct solves all of these problems, and looks like this:

if let Some(x) = optVal {
doSomethingWith(x);
}

关于rust - Rust 中的 match 和 if-let 之间的主要区别是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69161173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com