It is possible to generate some functions with names that came from a vector using a Rust macro?

Viewed 50

if I want to generate some functions using a macro, it is going to be like this:

macro_rules! generate_some_funcs {
    ($($func:ident),*) => {
        $(
            fn $func() {
                println!("I'm a function and my name is {}", stringify!($func));
            }
        )*
    }
}

generate_some_funcs!(a, b, c, d);

But, What if function names cames from a vector, array, or anything else? Is it possible?

fn main() {
  let func_names = vec!["a", "b", "c", "d"];

  generates_funcs!(func_names);
}
1 Answers

Function names cannot come from a vector, because vectors don't exist until runtime, and macros are evaluated at compile time. There isn't a syntax for iterating arrays in macros either.

What you can do is have the macro generate both the functions and the array. This way you don't have to duplicate the names.

macro_rules! generate_functions {
    ($var:ident => $($func:ident),*) => {
        $(
            fn $func() {
                println!("I'm a function and my name is {}", stringify!($func));
            }
        )*

        let $var = [$(stringify!($func)),*];
    }
}

fn main() {
    generate_functions!(func_names => a, b, c, d);

    a();
    b();
    c();
    d();

    assert_eq!(func_names, ["a", "b", "c", "d"]);
}
Related