Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper style to ignore a None value in Rust

Tags:

rust

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.

like image 373
Mark Pekala Avatar asked Oct 12 '25 12:10

Mark Pekala


1 Answers

if let could be helpful

for _whatever in something {
    if let Some(data) = foo() {
        // other stuff
    }
}
like image 87
Paul Avatar answered Oct 15 '25 16:10

Paul