Is there some better way to implement `array.every(predict)`

I want to test whether all elements in the array pass the some condition, and I used for loop :

pub fn main() {
    println!("{:?}", is_all_even());
}

pub fn is_all_even() -> bool {
    let arr = [2, 4, 6, 8];

    for num in arr {
        if num % 2 != 0 {
            return false
        }
    } 

    return true
}

When I used JavaScript, I can do that by Array.every:

arr.every(i => i % 2 === 0)

I guess this is a usual situation, but I not found method like arr.every in docs of Vec part. Did I go to the wrong way?

There is the all method of the Iterator trait you can call like this:

pub fn main() {
    println!("{:?}", is_all_even());
}

pub fn is_all_even() -> bool {
    let arr = [2, 4, 6, 8];

    arr.iter().all(|x| x % 2 == 0)
}

Playground.

5 Likes

In Rust, those sorts of "do something with each element" methods are lazy and implemented on the Iterator trait rather than attaching eager methods to the collection themselves.

One of the downsides of this approach is that you need to call iter() or into_iter() in order to get an iterator over the collection, and that extra half-dozen characters can feel cumbersome.

However, because Rust's iterators are lazy, you can now deal with infinite iterators or data that is generated on the fly without needing to create arrays with each set of intermediate results (i.e. your memory usage becomes closer to O(1) instead of O(n * num_ops)).

1 Like