gpt4 book ai didi

rust - 在 macro_rules 内匹配 - 不能使用 '_'

转载 作者:行者123 更新时间:2023-11-29 08:27:02 25 4
gpt4 key购买 nike

我正在尝试定义宏以简化枚举的创建可以转换为 str 或从 str 转换为:

macro_rules! define_enum_with_str_values {
($Name:ident { $($Variant:ident => $StrVar:expr),* $(,)* }) => {
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum $Name {
$($Variant),*,
}
impl Into<&'static str> for $Name {
fn into(self) -> &'static str {
match self {
$($Name::$Variant => $StrVar),*
}
}
}
impl FromStr for $Name {
type Err = BaseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let obj = match s {
$($StrVar => $Name::$Variant),*
};
Ok(obj)
}
}
}
}

define_enum_with_str_values!(Foo { Aa => "a", Bb => "b" });

这段代码没有编译,因为我没有定义'_'规则,但是如果我定义 '_' 规则:

    impl FromStr for $Name {
type Err = BaseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let obj = match s {
$($StrVar => $Name::$Variant),*
_ => {}
};
Ok(obj)
}
}

我遇到这样的编译时错误:

error: expected one of `!`, `,`, `.`, `::`, `?`, `{`, `}`, or an operator, found `_`
--> foo.rs:74:25
|
73 | $($StrVar => $Name::$Variant),*
| - expected one of 8 possible tokens here
74 | _ => {}
| ^ unexpected token
...
82 | define_enum_with_str_values!(Foo { Aa => "a", Bb => "b" });
| ----------------------------------------------------------- in this macro invocation

最佳答案

考虑当您展开那个宏时会发生什么。有问题的 match 看起来像:

let obj = match s {
"a" => Foo::Aa , "b" => Foo::Bb
_ => {}
};

请注意 "b"_ 臂之间缺少逗号。最简单的解决方法是确保每个 ARM 后始终有一个逗号:

let obj = match s {
$($StrVar => $Name::$Variant,)*
_ => return Err(BaseError)
};

关于rust - 在 macro_rules 内匹配 - 不能使用 '_',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49249085/

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