How do I call a function using the elements of an array as attributes

52 Views Asked by At

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.

0

There are 0 best solutions below