Is it possible to declare variables procedurally using Rust macros?

后端 未结 4 759
轮回少年
轮回少年 2020-11-27 07:55

Basically, there are two parts to this question:

  1. Can you pass an unknown identifier to a macro in Rust?

  2. Can you combine strings to generate

4条回答
  •  粉色の甜心
    2020-11-27 08:28

    In cases where concat_idents doesn't work (which is most cases I'd like to use it) changing the problem from concatenated identifiers to using namespaces does work.

    That is, instead of the non-working code:

    macro_rules! test {
        ($x:ident) => ({
            struct concat_idents!(hello_, $x) {}
            enum contact_idents!(hello_, $x) {}
        })
    }
    

    The user can name the namespace, and then have preset names as shown below:

    macro_rules! test {
        ($x:ident) => ({
            mod $x {
                struct HelloStruct {}
                enum HelloEnum {}
            }
        })
    }
    

    Now you have a name based on the macro's argument. This technique is only helpful in specific cases.

提交回复
热议问题