Search code examples
hashmaprustany

Check if any value in a Rust HashMap is greater than zero


I want to check if a HashMap<i32, i32> contains any values greater than zero. I have this code:

let has_demand = minimums.iter().any(|*x| x > 0)

which fails. The problem is with |*x|, but I don't know what to put there.


Solution

  • Bad syntax. You should use &x, which is a reference (not *x, which is a dereference).

    It is a HashMap (not a Vec), so to check values, you need to iterate through the values (not the entire HashMap).

    Example code:

    let value_exists = hashmap.values().any(|&x| x > 0);
    

    Please check out the docs: