I have a problem when I use macro_rules!.
I defined a enum Test and impl fmt for the enum.
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"),
}
}
}
Then I defined a macro print_test!.
macro_rules! print_test {
($test:pat) => {
println!("the Test is {}", $test);
};
}
However I got an error .
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
I'm a new Rustacean. And I really don't know why this happened.
update
I have already import the enum variants in a global scope.And following is the complete code
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);
}
Foo::Barinstead oruse Test::*and thenBar. I am pretty sure this is a duplicate, but can not yet find one. - justinas$testtoBar,the code can run without any error. - Huaiyu Gong