gpt4 book ai didi

rust - 怎么格式化! rust 宏规则中的 pat(enum)

转载 作者:行者123 更新时间:2023-12-03 11:29:59 24 4
gpt4 key购买 nike

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

我定义了一个 enum Test和实现 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);
}

最佳答案

只需更改 patexpr可以解决问题。

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com