Search code examples
rustanysyntactic-sugar

Is there an equivalent to the `any` method in python


There is a very convenient function called any in the standard library of Python, that allows to check given if any item in a given iterable verifies some condition.

my_list = [1, 3, 4, 5, 8]

# using any
four_is_present = any(elem == 4 for elem in my_list)

# is equivalent to
four_is_present = False
for elem in my_list:
    if elem == 4:
        four_is_present = True
        break

I am wondering if there is an equivalent syntactic sugar in Rust, or if I have to go for the "longer" expression.


Solution

  • Yes. There is Iterator::any which is a method on an Iterator (in contrast to Python where it is a free-standing function which accepts an Iterator).

    You can call it like any other method.

    fn main() {
        let my_list = vec![1, 3, 4, 5, 8];
        println!("{}", my_list.iter().any(|&i| i == 4));
    }
    

    If you are using a Vec or a slice anyway, you can use contains which will use the any method in its implementation.

    fn main() {
        let my_list = vec![1, 3, 4, 5, 8];
        println!("{}", my_list.contains(&4));
    }
    

    The API doc will also list other useful methods, e.g. all, chain, zip, map or filter. Also there are examples to those methods in the documentation which are all worth reading.