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?
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With