0

I'm new to rust and found myself tinkering with some macros. I decided, that I want to try making a macro, that can take an array and call a function, using the elements of that array as arguments for the function. This is what I have so far:

macro_rules! run {
  ( 
    $x:expr; $( $y:expr ),*
  ) => {
    $x( $($y),* )
  };
}

macro_rules! runArray {
    ($x:expr, $count:expr; $rest:expr) => {
        runArray!($x, $count-1; $rest, $rest[$count-1]);
    };
    ($x:expr, $count:expr; $rest:expr, $( $y:expr ),*) => {
        if $count == 0_u32 {
            run!($x; $($y),* ) // <-- this is where the error occures
        }
        else {
            runArray!($x, $count-1; $rest, $rest[$count-1], $($y),*)
        }
    };
}


fn test(msg: u32, foo: u32, bar: u32) {
    println!("{}, {}, {}", msg, foo, bar);
}

fn main() {
    let temp = vec![1, 2, 3];
    run!(test; temp[0], temp[1], temp[2]);
    runArray!(test, 3; temp);
}

The run! macro works fine but my runArray! macro spits out this error: error: recursion limit reached while expanding 'run!' on the line I commented on.

I really don't understand why this happens, because it should only recurse 3 times. Does anyone know what I did wrong here?

I tried to find a preexisting solution online before posting here, but I didn't find anything like this.

Luh0
  • 105
  • 8
  • 5
    The `if` isn't evaluated and neither is `$count - 1` it'll produce `3`, `3-1`, `3-1-1` ... never becoming `0` but always the literal calculation as macros always work on the AST. If you want to work with numbers you'll probably have to go into proc_macro land unless you want to define each number by itself. – cafce25 Aug 14 '23 at 12:16

0 Answers0