Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to count booleans in Rust?

Tags:

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?

like image 526
Elie Hess Avatar asked Oct 18 '25 10:10

Elie Hess


1 Answers

You could simply do:

let count = a as u8 + b as u8 + c as u8;
like image 70
Marco Bonelli Avatar answered Oct 22 '25 06:10

Marco Bonelli