如何在 Rust 中对“选项"分配进行分组? [英] How to group 'Option' assignments in Rust?
问题描述
我有一个代码块,其中需要一次分配多个可选变量.任何值都是 None
的可能性很小,因此单独处理每个失败的案例并不是特别有用.
I have a block of code where multiple optional variables need to be assigned at once. There is very little chance any of the values will be None
, so individually handing each failed case isn't especially useful.
目前我写的支票是这样的:
Currently I write the checks like this:
if let Some(a) = foo_a() {
if let Some(b) = foo_b() {
if let Some(c) = foo_c() {
if let Some(d) = foo_d() {
// code
}
}
}
}
如果可以对作业进行分组会很方便.如果没有这个,添加一个新变量会使块缩进一级,从而产生嘈杂的差异并导致不必要的深度缩进:
It would be convenient if it was possible to group assignments. Without this, adding a new variable indents the block one level, making for noisy diffs and causes unnecessarily deep indentation:
if let Some(a) = foo_a() &&
let Some(b) = foo_b() &&
let Some(c) = foo_c() &&
let Some(d) = foo_d()
{
// code
}
有没有办法在一个 if 语句中分配多个 Option
?
Is there a way to assign multiple Option
s in one if statement?
一些值得注意的细节:
第一个失败的函数应该短路而不是调用其他函数.否则,它可以写成这样:
The first function that fails should short circuit and not call the others. Otherwise, it could be written like this:
if let (Some(a), Some(b), Some(c), Some(d)) = (foo_a(), foo_b(), foo_c(), foo_d()) {
// Code
}
使用函数可以避免深度缩进,但我不希望这样做,因为您可能不希望正文处于不同的范围...
Deep indentation could be avoided using a function, but I would prefer not to do this since you may not want to have the body in a different scope...
fn my_function(a: Foo, b: Foo, c: Foo, d: Foo) {
// code
}
if let Some(a) = foo_a() {
if let Some(b) = foo_b() {
if let Some(c) = foo_c() {
if let Some(d) = foo_d() {
my_function(a, b, c, d);
}
}
}
}
推荐答案
正如 @SplittyDev 所说,你可以创建一个宏来获得你想要的功能.这是一个替代的基于宏的解决方案,它也保留了短路行为:
As @SplittyDev said, you can create a macro to get the functionality you want. Here is an alternate macro-based solution which also retains the short-circuiting behaviour:
macro_rules! iflet {
([$p:pat = $e:expr] $($rest:tt)*) => {
if let $p = $e {
iflet!($($rest)*);
}
};
($b:block) => {
$b
};
}
fn main() {
iflet!([Some(a) = foo_a()] [Some(b) = foo_b()] [Some(c) = foo_c()] {
println!("{} {} {}", a, b, c);
});
}
这篇关于如何在 Rust 中对“选项"分配进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!