我在使用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/