繁体   English   中英

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

[英]match inside macro_rules - can not use '_'

我试图定义宏以简化枚举的创建,该枚举可以转换为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"_臂之间没有逗号。 最简单的解决方法是确保每条手臂后总是有一个逗号:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM