Elie Hess
Elie Hess

Reputation: 83

Is there an easy way to count booleans in Rust?

I've encountered a scenario in which I have a known, small number of boolean values, but I don't care about them individually, I just want to determine how many of them are true. It seems like there should be a fast way of doing this, but the best I can come up with is the naive solution:

let mut count: u8 = 0;
if a {
    count += 1;
}
if b {
    count += 1;
}
if c {
    count += 1;
}

Is there a better way of doing this?

Upvotes: 4

Views: 3738

Answers (2)

anw
anw

Reputation: 410

I'd like to point you to Michael Anderson's post, which gives a much nicer syntax than mine.

let a = true;
let b = false;
let c = true;
let d = true;
let e = false;

let total_true = [a, b, c, d, e].into_iter().filter(|b| *b).count();

println!("{} options are true!", total_true);

I've left my original answer below for posterity

Original Answer


One option is to put your booleans into a Vector, then filter based on if they're true or not.

    let options = vec![true, false, true, false, false, false, true];
    let total_true = options.into_iter()
                            .filter(|b| *b)
                            .collect::<Vec<bool>>()
                            .len();

    println!("{} options are true!", total_true);

We need to convert Vec into an iter, so we can run filter on it.

Then, since filter checks for true boolean expressions, we simply deref our item as *b to get the non-borrowed boolean value.

Then we collect that back into a Vector, and get the length to find out how many met our criteria (of being true).

This gives you the total number of true booleans.

Upvotes: 5

Marco Bonelli
Marco Bonelli

Reputation: 69276

You could simply do:

let count = a as u8 + b as u8 + c as u8;

Upvotes: 5

Related Questions