0

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.

cyvb
  • 3
  • 2

1 Answers1

0

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)?, )*)) })());
}
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77