1

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?

3
  • The $() around the match arms is redundant, but also why are you matching $val then doing an additional $val == true and $val == false check? Commented Jan 30, 2021 at 2:30
  • is a macro necessary? can't this be done with a normal function? Commented Jan 30, 2021 at 2:52
  • @kmdreko it could be but I like to use macros for all my debugging Commented Jan 30, 2021 at 2:55

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)),+,) }; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.