Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 333
Yuri Geinish Avatar asked Apr 11 '18 21:04

Yuri Geinish


2 Answers

unwrap_or_else is just a convenience method around a match usually used in method call chains. 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:

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

    // other stuff
}
like image 191
mcarton Avatar answered Oct 09 '22 13:10

mcarton


To be explicit, unless I misunderstand @mcarton's answer, the match statement for continuing on an error and keeping a result if not:

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.

like image 1
Nathaniel Ford Avatar answered Oct 09 '22 13:10

Nathaniel Ford