在 Rust 宏中检查 bool 的值

Check Value of bool in Rust Macro

我想创建一个宏来检查提供的布尔值和 returns 基于该值的字符串。我试过这个:

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

}

但这给了我错误:

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

在我的宏中使用相等运算符比较 $var 的正确方法是什么?

你只匹配 $val,没有特殊的语法。

macro_rules! dbg_bool{
    () => {};
    ($val:expr $(,)?) => {
        match $val {
            true => {
                "it was true"
            }
            false =>{
                "it was false"
            }
        }
    };
    ($($val:expr),+ $(,)?) => {
        ($(dbg_bool!($val)),+,)
    };
}

match 语法在宏中没有改变:

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

顺便说一句,当您使用宏时,您假设给您 greenblue 的特征在范围内。为了稳健性,您需要像 ::colored::Colorize::green("it was true") 一样显式调用它,或者将 match 包装在一个块中,以便您可以添加 use ::colored::Colorize; (假设您使用的是 colored crate). See these two options on the playground.