Macro match with literal call with ident

Is there any way to have a macro that match against literal's value but is called with an ident? I do not think so because when expanded there is no way for the compiler to know what that ident stand for, asking because pretty new to rust and not very comfortable with macros.

macro_rules! do_somthing {
    (0) => {type Abc = String};
    (1) => {type Abc = u64};
}

/// Calling do_something with literals is ok
do_something(0)

// Calling with idents no
const VAL: i32 = 1;
do_something(VAL)

I think that there is no way to use match or if inside the macro because I need to return items.

More context

I put this section because maybe due to my inexperience I'm trying to solve a problem in a very strange way and there is an obvious and very simpler way to do what I'm trying to do.

I come up with this (non)solution because I need a macro to define types and struct. The macro accept some values for example (a, b) what I need is a and also a + b, a and b are both literals, to do the sum I create a const VAL: i32 = a + b in the called macro and then I call another macro passing the const name (VAL). In the second macro I need to match against values because different struct are created for each number in the range 0..39, but the first macro can only call the second passing an ident because I need to sum a and b. Passing (a, a+b) is not a solution because very error pron, usability of the macro and readability of the code that use the macro.

Ty :slight_smile:

Macros are evaluated before everything else, before const items, before variables, before types. They only see literal text (tokens) you pass to them, and don't understand what that text means.

You can still have a macro that takes two expressions and adds them together in the code generated by the macro. It's only you can't see the sum in the macro pattern, because the sum will be calculated after the macro has finished.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.