Search code examples
rustoption-type

Is there a concise way to check if an Option is None or if its Some contents are empty?


Is there something more concise that the below code?

let player_list: Option<Vec<Player>>;

// more code here

if player_list.is_none() || player_list.as_ref().unwrap().is_empty() {
  // do something here if player_list is none or empty
}

I would like to avoid the || part.


Solution

  • I assume you probably don't want player_list to be consumed. In that case, use:

    player_list.as_ref().map_or(true, Vec::is_empty)
    

    if it's ok to consume player_list:

    player_list.unwrap_or_default().is_empty()