简体   繁体   English

可以使用 Rust 宏生成一些名称来自向量的函数吗?

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

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);
}

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"]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM