How pass string pattern to macro

I know how use macro but how fix this
macro_rules! foo {
(x => $e:expr) => {// do some things };
(y => $e:expr) => {// do some things };
}
fn main() {
let pattern = “x => 3”; // how pass this string to foo! ???
foo!(pattern); // no rules expected this token in macro call
}

Macros are purely a syntax thing, evaluated at compile time. They can’t parse any values from variables. You have to do foo!(x => 3); without any indirection.

1 Like

Aside:

If you put three backticks on its own line,

like
  this

it’ll preserve the indentation in your code

macros examine syntactic tokens, so the only way to analyse a “string” would be with string literals. Then, macro_rules macros don’t offer that level of inspection, so you would need a proc-macro function-like macro to do so.

So the problem comes from inspecting strings with a macro. Change one of these two things and it will be much easier:

  • no macro

    Inspecting strings (literals or not), can be done with classic functions:

    fn foo (s: &str)
    {
        const X_PREFIX: &str = "x => ";
        const Y_PREFIX: &str = "y => ";
        if s.starts_with(X_PREFIX) {
            let expr: &str = &s[X_PREFIX.len() ..];
            // ...
        } else if s.starts_with(Y_PREFIX) {
            let expr: &str = &s[Y_PREFIX.len() ..];
            // ...
        } else {
            // ...
        }
    }
    
  • do not use strings

    macro_rules! foo {
        (x => $e:expr) => ({/* do some things */});
        (y => $e:expr) => ({/* do some things */});
    }
    
    fn main ()
    {
        foo!(x => 3);
    }
    
1 Like

thanks