【问题标题】:Inverse `?` operator in Rust (aka return if Some/Ok)Rust 中的反向 `?` 运算符(如果 Some/Ok 则返回)
【发布时间】:2022-12-08 02:43:25
【问题描述】:

我正在使用 syn 构建宏解析器,需要检查 ParseStream 是否是多个 keywords 之一。该代码目前看起来类似于:

mod kw {
    syn::custom_keyword!(a);
    syn::custom_keyword!(b);
    syn::custom_keyword!(c);
}

enum MyKeywordEnum {
    A(kw::a),
    B(kw::b),
    C(kw::c),
}

impl syn::parse::Parse for MyKeywordEnum {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        Ok(if let Ok(ret) = input.parse::<kw::a>() {
            Self::A(ret)
        } else if let Ok(ret) = input.parse::<kw::b>() {
            Self::B(ret)
        } else if let Ok(ret) = input.parse::<kw::c>() {
            Self::C(ret)
        } else {
            abort!(input.span(), "Couldn't parse primitive type"); // Via #[proc_macro_error]
        })
    }
}
  • 如果表达式是Option::SomeResult::Ok,是否有内置运算符或宏立即返回?
  • 有没有更好的方法来组织这些检查?
  • 因为ParseStream::parse静态编译为特定的impl Parse类型,我不能使用match,对吧?

【问题讨论】:

    标签: rust rust-proc-macros


    【解决方案1】:

    据我所知,没有。您可以创建一个宏来执行此操作,或者您可以使用 Result 组合器函数使事情变得更漂亮:

    impl syn::parse::Parse for MyKeywordEnum {
        fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
            input.parse::<kw::a>().map(Self::A)
                .or_else(|_| input.parse::<kw::b>().map(Self::B))
                .or_else(|_| input.parse::<kw::c>().map(Self::C))
                .or_else(|_| abort!(input.span(), "Couldn't parse primitive type"))
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 2020-05-12
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 2018-07-08
      相关资源
      最近更新 更多