有没有在声明式宏迭代中进行“早期返回”的方法?

huangapple go评论53阅读模式
英文:

Is there any way to "early return" in a declarative macro iterations?

问题

我对Rust的宏很陌生。

我想找到一种实现类似这样行为的方法:在迭代中提前返回

我学到了我可以使用像这样的声明性宏生成元组:

fn function(input) -> Result<input_type, err_type> {
    // 做一些事情
}

macro_rules! to_tuple {
    ($($input:expr),*) => (($( function($input), )*));
}

fn main() {
    to_tuple!(i_1, i_2);
    // 我会得到一个元组: (o_1, o_2)
}

现在我想在每次迭代中检查function的结果。如果它们都正常,我将得到一个Ok(tuple)。如果发生错误,我将得到一个Err(string)。就像这样:

to_tuple!(right_1, right_2) => Ok( (o_1, o_2) )
to_tuple!(right_1, right_2, right_3) => Ok( (o_1, o_2, o_3) )
to_tuple!(right_1, wrong_1, right_2) => Err( string )

使用声明性宏是否可能实现这个目标?

我认为宏生成的不是真正的迭代,所以没有迭代,因此显然没有"提前返回"。我希望我是错的。如果有人有任何想法,请告诉我。

英文:

I'm new to Rust's macros.

I'd like to find a way to achieve a behaviour like this: early return in iterations

I learned I can generate tuples using a declarative macro like this one:

fn function(input) -&gt; Result&lt;input_type,err_type&gt; {
    // do something
}

macro_rules! to_tuple {
    ($($input:expr),*) =&gt; (($( function($input), )*));
}

fn main() {
    to_tuple!(i_1, i_2);
    // I will get a tuple: (o_1, o_2)
}

Now I'd like to check result of function in every iteration. If they are all ok, I'll get a Ok(tuple). If error occurs, I'll get a Err(stirng). Like:

to_tuple!(right_1, right_2) =&gt; Ok( (o_1, o_2) )
to_tuple!(right_1, right_2, right_3) =&gt; Ok( (o_1, o_2, o_3) )
to_tuple!(right_1, wrong_1, right_2) =&gt; Err( string )

Is this possible using declarative macros?

I think what macros produces is not real iterations, so there is no iterations, therefore apparently there is no "early return". I wish I were wrong. If anyone has any idea, please tell me.

答案1

得分: 0

这将是一个完美的地方,适用于try。 除了它们是不稳定的。 但我们可以用一个闭包来模拟它们:

macro_rules! to_tuple {
    ($($input:expr),*) => ((|| -> Result<_, String> { Ok(($( function($input)?, )*)) })());
}
英文:

This would be a perfect place for try blocks. Except they're unstable. But we can emulate them with a closure:

macro_rules! to_tuple {
    ($($input:expr),*) =&gt; ((|| -&gt; Result&lt;_, String&gt; { Ok(($( function($input)?, )*)) })());
}

huangapple
  • 本文由 发表于 2023年2月27日 02:26:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75574147.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定