Iterator find - referencing the needle instead of dereferencing the iterating item


#1

Consider the following code:

fn main() {
    let greater_than_42 = (0..100).find(|x| *x > 42);
    match greater_than_42 {
        Some(x) => println!("{}", x),
        None => println!("no numbers found"),
    }
}

If I do this instead:

    let greater_than_42 = (0..100).find(|x| x > &42);

would it compare memory addresses, instead of values?


#2

No, references compare like the underlying type. Cast to raw pointers (*const _) if you want to compare pointers.


#3

As an alternative, you can also do it with pattern matching:

let greater_than_43 = (0..100).find(|&x| x > 42);