【问题标题】:How do you handle errors inside a Rust filter()?你如何处理 Rust filter() 中的错误?
【发布时间】:2023-04-09 14:43:01
【问题描述】:

我想使用一个可能返回Err 结果的过滤器函数,并将其冒泡到包含函数:

mycoll.into_iter()
  .filter(|el| {
    if el == "bad" {
      Err(MyError)
    } else {
      Ok(el < "foo")
    }
  })

当涉及到map()(使用.collect::&lt;Result&lt;...&gt;&gt;())时,我找到了一个很好的解释:How do I stop iteration and return an error when Iterator::map returns a Result::Err?,但我无法为filter()找到类似的解决方案。

这里的惯用解决方案是什么?

【问题讨论】:

    标签: filter error-handling rust iterator


    【解决方案1】:

    我可能会建议使用filter_map。您的示例如下所示:

    mycoll.into_iter()
      .filter_map(|el| {
        if el == "bad" {
          Some(Err(MyError))
        } else if el < "foo" {
          Some(Ok(el))
        } else {
          None
        }
      })
    

    【讨论】:

      猜你喜欢
      • 2015-06-18
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多