[英]Rust if let Optionals and compare conditions
I have a lot of code like this, and would like to replace with a "if let"
binding for clarity in my case我有很多这样的代码,在我的案例中为了清楚起见,我想用
"if let"
绑定替换
// 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?
}
Not sure on the syntax to bind the let with a comparison:不确定用比较绑定 let 的语法:
if let (Some(a),Some(b) = (maybe_num_A, maybe_num_B) ???&&??? a > b {
...
}
If you're only comparing A
and B
and do not necessarily need to bind them, you could use the .zip
method that's in Rust 1.46 and apply a map_or
on it, eg:如果您只比较
A
和B
并且不一定需要绑定它们,则可以使用Rust 1.46中的.zip
方法并在其上应用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
}
If either of the two values is None
, it will default to false
.如果两个值中的任何一个为
None
,它将默认为false
。
Not sure on the syntax to bind the let with a comparison:
不确定用比较绑定 let 的语法:
Unfortunately there isn't any.不幸的是没有。 If you need to access bindings from the pattern, you have to do it the old fashioned way:
如果您需要从模式访问绑定,则必须以老式的方式进行:
if let (Some(a), Some(b)) = (maybe_num_A, maybe_num_B) {
if a > b {
...
}
}
If you don't need the bindings from the pattern then Jason's answer will do the job and might end up cleaner, as long as the actual patterns are relatively simple.如果您不需要模式中的绑定,那么只要实际模式相对简单,杰森的答案就可以完成工作并且最终可能会更干净。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.