I'm new to Rust and looking for good style options to handle following:
Let's say that foo
returns Option<i32>
. I'm calling foo
in a loop and in the case that it returns None
I simply want to move on. Right now I find myself doing something like:
for _whatever in something {
let data = foo();
if data.is_none() {
continue;
}
let data = data.unwrap();
// other stuff
}
Not bad, pretty readable, but I can't help but feeling like it could be more concise. This feels like a pretty common use case, and I was wondering what other options I might have to achieve something similar, and if there was an accepted best practice for dealing with None
in this way.
I've tried using match
statements and conditionals on is_none
, finding the later slightly preferable.
if let
could be helpful
for _whatever in something {
if let Some(data) = foo() {
// other stuff
}
}
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