Is there an idiomatic way to convert empty Vec to None?

Viewed 469

I have a closure in a filter_map that ends in this if statement:

if my_vec.is_empty() {
    None
} else {
    Some(my_vec)
}

Is there a simple way to convert an empty Vec into either a None or a Some(my_vec)?

2 Answers

There is a function in impl bool called then which converts a bool to an option.

let opt = (!my_vec.is_empty()).then(|| my_vec);

There is also then_some, available in nightly.

#![feature(bool_to_option)] 
fn main() {
    let my_vec: Vec<i32> = vec![];
    let _opt = (!my_vec.is_empty()).then_some(my_vec);
}

Since you mentioned filter_map, what about changing

sth.filter_map(|item| {
  let my_vec = some_operation(item);
  if my_vec.is_empty() {
    None
  } else {
    Some(my_vec)
  }
})

to

sth
.map(|item| some_operation(item))
.filter( |vec| !vec.is_empty())

According to official doc, Rust's iterators are zero-cost abstraction, so you can do this without extra cost.

Related