Option { Some(1)} let maybe_n-6ren">
gpt4 book ai didi

Rust if let Optionals 和比较条件

转载 作者:行者123 更新时间:2023-12-03 11:32:34 24 4
gpt4 key购买 nike

我有很多这样的代码,我想用 "if let" 绑定(bind)来替换我的情况以清晰明了

// contrived
fn maybe() -> Option<i32> { Some(1)}
let maybe_num_A = maybe();
let maybe_num_B = maybe();
...
match (maybe_num_A, maybe_num_B) {
(Some(a) , Some(b)) if a > b => {
....
}
_ => {} // don't care many times about the other matches that doesn't hold. how to get rid of this?
}

不确定用比较绑定(bind) let 的语法:

if let (Some(a),Some(b) = (maybe_num_A, maybe_num_B) ???&&??? a > b {
...
}

最佳答案

如果您只是比较AB 并且不一定需要绑定(bind)它们,您可以使用.zip Rust 1.46 中的方法并申请 map_or在上面,例如:

let a: Option<i32> = Some(42);
let b: Option<i32> = Some(-42);

if a.zip(b).map_or(false, |(a, b)| a > b) {
// 42 is greater than -42
}

如果两个值中的任何一个为None,它将默认为false

关于Rust if let Optionals 和比较条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64522168/

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