Reputation: 3401
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?
Upvotes: 1
Views: 1524
Reputation: 59912
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.
Upvotes: 2
Reputation: 2192
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)),+,)
};
}
Upvotes: 0