What's the most efficient way to implement boolean masking with vectors in Rust?
There might be a crate that does this(?), but to help me learn, I'd also like to hear about:
- how you'd do this without a crate (i.e. have I missed something in the standard library?), and;
- whether bool masking can be extended to lists and iterators more generally.
My example below applies the bool vector [true, false, false, true] to mask out the true indices of a u32 vector [1, 2, 3, 4]. This returns [2, 3].
I'm using a clunky for loop; can we do it better using e.g. maps and iterators?
fn main() {
let mut numbers = vec![1, 2, 3, 4];
let mask = vec![true, false, false, true];
remove_true(&mut numbers, &mask); // remove numbers where vector mask == true
println!("{:?}", numbers)
}
// Using a for loop
fn remove_true(vec: &mut Vec<u32>, locs: &Vec<bool>) {
for m in (0..locs.len()).rev() {
// Loop in reverse to preserve indices when dropping values
if locs[m] == true {
vec.remove(m);
}
}
}