Search code examples
loopsrustvector

Bitwise operation for all elements of a vector


For a Vec<u32> of undefined size, what is the Rust way of calling a bitwise (and, or, xor, etc.) operator on all of them, and returning with the resulting data?

I understand it is possible with a simple loop, what I'm looking for is the Rust way™.


Solution

  • You can use Iterator::fold. For example with bitwise or, |:

    pub fn main() {
        let a = vec![1, 2, 4, 8];
    
        let sum = a.iter().fold(0, |acc, x| acc | x);
    
        assert_eq!(sum, 15);
    }
    

    (Example taken from https://doc.rust-lang.org/std/iter/trait.Iterator.html#examples-38 and adjusted.)