Search code examples
macrosrustrust-macros

How do I test if a identifier in a macro starts with an underscore?


I need to check whether the identifier begins with an underscore. This does not work:

#[macro_export]
macro_rules! UNDECORED {
    (_$_i:ident) => {... do something if underscored};
    ($_i:ident) => {... do something else};
}

Where is the mistake?


Solution

  • Macros receive "tokens" as input; the leading underscore is not a separate token, and you cannot match partial tokens.

    You could stringify! the identifier and match the name at runtime.