rust - 怎么格式化啊! rust Macro_rules 中的 pat(enum)

标签 rust rust-macros

我在使用macro_rules!时遇到问题。

我定义了一个枚举测试并为枚举实现了fmt

 use core::fmt;
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub enum Test {
        Foo(String),
        Bar,
    }
    impl fmt::Display for Test {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                Test::Foo(id) => write!(f, "Foo({})", id),
                Test::Bar => write!(f, "Bar"),
            }
        }
    }

然后我定义了一个宏print_test!

macro_rules! print_test {
    ($test:pat) => {
        println!("the Test is {}", $test);
    };
}

但是我遇到了错误。

error: expected expression, found `Bar`
  --> src/main.rs:53:36
   |
53 |         println!("the Test is {}", $test);
   |                                    ^^^^^ expected expression
...
57 |     print_test!(Bar);
   |     ----------------- in this macro invocation

我是一名新 Rustacean。我真的不知道为什么会发生这种事。


更新

我已经在全局范围内导入了枚举变体。以下是完整的代码

mod test {
    use core::fmt;
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub enum Test {
        Foo(String),
        Bar,
    }
    impl fmt::Display for Test {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                Test::Foo(id) => write!(f, "Foo({})", id),
                Test::Bar => write!(f, "Bar"),
            }
        }
    }
}
use test::Test::*;
macro_rules! print_test {
    ($test:pat) => {
        println!("the Test is {}", $test);
    };
}
fn main() {
    let a=String::from ("test");
    print_test!(Bar);
}

最佳答案

只需将pat更改为expr即可解决问题。

macro_rules! print_test {
    ($test:expr) => {
        println!("{}",$test);
    };
}

关于rust - 怎么格式化啊! rust Macro_rules 中的 pat(enum),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61768445/

相关文章:

rust - 如何使内部函数不公开?

rust - rust 编译器如何生成 "immutable borrow occurs here"?

templates - 如何在 Rust 中使用数值作为泛型参数?

rust - 递归宏的困难

for-loop - 如何循环特定(可变)次数?

rust - 我如何强制执行父子结构生命周期?

debugging - 如何查看导致编译错误的扩展宏代码?

struct - 如何在不为每个字段重复 `pub` 的情况下创建所有字段都是公共(public)的公共(public)结构?

rust - 创建自定义彩色 dbg! Rust 中的宏

rust - extern crate 语句前的#[macro_use] 是什么意思?