Search code examples
rustrust-macros

Is it possible to ignore Rust's exponents?


I am trying to use the letter "E" within a Rust macro without triggering mathematical exponents. Here is an example:

macro_rules! test {
  (0e) => {
    // Do something
  };
}

fn main() {
  test!(0e);
}

This gives the error error: expected at least one digit in exponent. Is it possible to ignore? I know I can write this is other ways, but I would prefer to write it in this way due to consistency.

Thank you.


Solution

  • Macro input is a sequence of token trees that have been parsed using the same tokenizer that is used for Rust code. While you can create new syntax with macros, you are still limited to only handling tokens that are valid tokens in Rust.

    Even a procedural macro can't do this because the error happens in the code that calls the macro, before it ever sees the input.

    The workaround is to require that the input is a string. A procedural macro can then parse this however you like.