Search code examples
rustrust-macrosrust-decl-macros

How do I get an identifer from an expression argument in a macro?


I have a constant value defined by a variable:

const VAL: usize = 32;

I want to make a function like this:

macro_rules! valfn {
    ($val:expr) => {
        pub fn $val () -> () {   // here val needs to be a ident
            some_other_fn($val)  // here it needs to be a expr
        }
    };
}

valfn!(VAL);

Bonus points if I can do some manipulation of the ident value one way or the other to avoid clashing definitions. Could I shadow a variable with a function definition? Probably not...

const VAL: usize = 32;
valfn!(VAL); // creates: fn VAL()

or

const VAL_: usize = 32;
valfn!(VAL_); // creates: fn VAL()

Solution

  • In the macro, an ident is a valid expr, so you can just use ident.

    macro_rules! valfn {
        ($val: ident => {
            pub fn $val () -> () {
                some_other_fn($val)
            }
        };
    }
    

    You can add a module to avoid naming conflicts, or any of the other suggestions from Shepmaster's answer.