Is there a simple way to find out whether a Vector is filled with None in Rust?

Viewed 1087

Given a Vector of Option<T> in Rust, is there a simple way to check whether the Vector is filled with None?

For instance, I can find a simple way to check whether a Vector is filled with Some(usize).

fn main() {
    let x: Vec<Option<usize>> = vec![None, None, Some(3)];
    if x.contains(&None) {
        println!("The Vector is not filled with Some(usize)!");
    }else {
        println!("The Vector is filled with Some(usize)!");
    }
}

However, If I replace &None to &Some(usize) in that code, I get an error.

fn main() {
    let x: Vec<Option<usize>> = vec![None, None, Some(3)];
    if x.contains(&Some(usize)){
        println!("The Vector is not filled with None!");
    }else {
        println!("The Vector is filled with None!");
    }
} 
   Compiling playground v0.0.1 (/playground)
error[E0423]: expected value, found builtin type `usize`
 --> src/main.rs:3:25
  |
3 |     if x.contains(&Some(usize)){
  |                         ^^^^^ not a value

As workaround, I could just count the number of None and compare it to x.len().

fn main() {
    let x: Vec<Option<usize>> = vec![None, None, Some(3)];
    if x.iter().filter(|x| **x==None).count() == x.len(){
        println!("The Vector is filled with None!");
    }else {
        println!("The Vector is not filled with None!");
    }
}

And... it looks overly complex. Is there a way to fix that error so the code works as desired? If not, is there more concise or simpler way to do this in Rust?

1 Answers

You can use all:

fn main() {
    let x: Vec<Option<usize>> = vec![None, None, Some(3)];
    if x.iter().all(|x| x.is_none()) {
        println!("The Vector is filled with None!");
    } else {
        println!("The Vector is not filled with None!");
    }
}

Or flatten:

fn main() {
    let x: Vec<Option<usize>> = vec![None, None, Some(3)];
    if x.iter().flatten().next().is_none() {
        println!("The Vector is filled with None!");
    } else {
        println!("The Vector is not filled with None!");
    }
}
Related