0

I'd like to create a macro that checks the value of a provided bool and returns a string based on that value. I tried this:

macro_rules! dbg_bool{
    () => {};
    ($val:expr $(,)?) => {
        match $val {
            //if $val is true return a green string
            $($val == true) => {
                "it was true".green()
            }
            //if $val is false return a red string
            $($val == false) =>{
                "it was false".red()
            }
        }
    };
    ($($val:expr),+ $(,)?) => {
        ($(dbg_bool!($val)),+,)
    };

}

but this gives me the error:

error: expected one of: `*`, `+`, or `?`
  --> src/macros.rs:28:32
   |
28 |               $($val == true) => {
   |  ________________________________^
29 | |                 "it was true".green()
30 | |             }
   | |_____________^

What's the proper way to use equality operators to compare the $var in my macro?

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
ANimator120
  • 2,556
  • 1
  • 20
  • 52

2 Answers2

2

The match syntax doesn't change in a macro:

macro_rules! dbg_bool{
    () => {};
    ($val:expr $(,)?) => {
        match $val {
            //if $val is true return a green string
            true => {
                "it was true".green()
            }
            //if $val is false return a red string
            false => {
                "it was false".red()
            }
        }
    };
    ($($val:expr),+ $(,)?) => {
        ($(dbg_bool!($val)),+,)
    };
}

As an aside, you are assuming the trait that gives you green and blue are in scope when you use the macro. For robustness, you'll want to either call it explicitly like ::colored::Colorize::green("it was true") or wrap the match in a block so you can add a use ::colored::Colorize; (assuming you're using the colored crate). See these two options on the playground.

kmdreko
  • 42,554
  • 6
  • 57
  • 106
0

You just match on $val, there is no special syntax.

macro_rules! dbg_bool{
    () => {};
    ($val:expr $(,)?) => {
        match $val {
            true => {
                "it was true"
            }
            false =>{
                "it was false"
            }
        }
    };
    ($($val:expr),+ $(,)?) => {
        ($(dbg_bool!($val)),+,)
    };
}
Ivan C
  • 1,772
  • 1
  • 8
  • 13