简体   繁体   English

Rust 从闭包内部继续使用的方式是什么?

[英]What is the Rust way of using continue from inside a closure?

This isn't possible, but very much desired:这是不可能的,但非常需要:

loop {
    something().unwrap_or_else(|err| {
        warn!("Something bad happened: {}", err);
        continue;
    });

    // other stuff
}

What is the Rust way of solving it? Rust的解决方法是什么?

unwrap_or_else is just a convenience method around a match usually used in method call chains. unwrap_or_else只是一种方法调用链中常用的match方法。 As this is not the case here, you can simply use a match instead, and since you only seem to be interested by the Err case, you can also use if let : 由于这不是这种情况,你可以简单地使用match ,因为你似乎只对Err情况感兴趣,你也可以使用if let

loop {
    if let Err(err) = something() {
        warn!("Something bad happened: {}", err);
        continue;
    }

    // other stuff
}

To be explicit, unless I misunderstand @mcarton's answer, the match statement for continuing on an error and keeping a result if not:明确地说,除非我误解了@mcarton 的回答,否则匹配语句会继续出错并保留结果(如果不是):

fn looper() {
  loop {
    let res = match subcommand() {
        Ok(v) => v,
        Err(e) => {
          warn!("Uh oh: {}", e);
          continue;
        }
    }
    ...  // `res` is usable here, unwrapped.
  }
}

// For demonstration only - types may vary
fn subcommand() -> Result<String> {
  ... // some code that returns either Ok(some_string) or Err(msg)
}

And that there is not really a way to shorthand it more than that.并且没有其他方法可以简化它。

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

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