Search code examples
rustlet

"no rules expected the token" when writing a `let` statement in a macro


When I try to compile this code using rustc main.rs:

macro_rules! getPI {
    let pi = 3.141592;
    println!("Pi is roughly 3.142 \n {0}", pi);
}

fn main() {
    print!(getPI);
}

it gives me an error:

error: no rules expected the token `pi`
 --> src/main.rs:2:9
  |
2 |     let pi = 3.141592;
  |         ^^

I'm very new to programing, I hope someone has a solution.


Solution

  • If you are "very new to programing", then you should start at the beginning; macros are not the beginning. Go back and re-read The Rust Programming Language, second edition, even though it's targeted at people who already understand another programming language.

    You can then read the chapter from the first edition about macros. This will show you the proper syntax for macros. Macros have a number of arms, like a match statement:

    macro_rules! getPI {
        () => {
            let pi = 3.141592;
            println!("Pi is roughly 3.142 \n {0}", pi);
        }
    }
    
    fn main() {
        getPI!();
    }
    

    I also don't know why you'd try to print! the return value of your macro, so I removed that. You must also call the macro using an exclamation mark (!).