Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何格式化!rust宏_规则中的pat(枚举)_Rust_Rust Macros - Fatal编程技术网

如何格式化!rust宏_规则中的pat(枚举)

如何格式化!rust宏_规则中的pat(枚举),rust,rust-macros,Rust,Rust Macros,我在使用宏规则时遇到问题 我为枚举定义了enum测试和implfmt 使用core::fmt; #[派生(调试、克隆、PartialEq、Eq)] pub枚举测试{ 傅(弦), 酒吧, } impl fmt::用于测试的显示{ fn fmt(&self,f:&mut fmt::Formatter)->fmt::Result{ 匹配自我{ 测试::Foo(id)=>write!(f,“Foo({})”,id), Test::Bar=>write!(f,“Bar”), } } } } 使用测试::测

我在使用宏规则时遇到问题

我为枚举定义了
enum测试和impl
fmt

使用core::fmt;
#[派生(调试、克隆、PartialEq、Eq)]
pub枚举测试{
傅(弦),
酒吧,
}
impl fmt::用于测试的显示{
fn fmt(&self,f:&mut fmt::Formatter)->fmt::Result{
匹配自我{
测试::Foo(id)=>write!(f,“Foo({})”,id),
Test::Bar=>write!(f,“Bar”),
}
}
}
}
使用测试::测试::*;
宏规则!打印测试{
($test:pat)=>{
println!(“测试为{},$Test);
};
}
fn main(){
设a=String::from(“test”);
打印测试!(条形图);
}

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

macro\u规则!打印测试{
($test:expr)=>{
println!(“{}”,$test);
};
}

默认情况下,枚举变量不在全局范围内。尝试使用
Foo::Bar
,或者
使用Test:*
然后使用
Bar
。我很确定这是一个复制品,但还没有找到。这能回答你的问题吗?很抱歉,我忘了发布完整的代码。我已经在全局范围内导入了枚举变量。如果我将
$test
更改为
Bar
,代码可以毫无错误地运行。我不明白为什么要使用
pat
path
:在扩展中,
$test
只是一个表达式/值(RHS)
pat
是一个模式(LHS,分配的目标或匹配臂的模式),而
path
是一个qname。为什么不将
$test
声明为
expr
。而且,你只发布一些小片段和小片段是非常不方便的,读者必须尝试重新构建它周围的内容。发布一个完整的测试用例(减少到显示问题的最低限度),最好是放在游乐场链接旁边,这对读者来说非常有用。谢谢,
expr
对我很有用。这是我第一次在stackoverflow中问问题(>~好!问题已经解决。我会更改答案。谢谢你的提醒。