英文:
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) -> Result<input_type,err_type> {
// do something
}
macro_rules! to_tuple {
($($input:expr),*) => (($( 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) => 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 )
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),*) => ((|| -> Result<_, String> { Ok(($( function($input)?, )*)) })());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论