Vec, filter and references question


#1

Hi,
I have a question about references, Vec and the filter method:

let a = [0, 1, 2, 11, 444];
let nums = a.iter().filter( | x | **x > 10).collect::<Vec<&i32>>();

This is easy and according to the docs I either can do *xx or inside the closure parameter write |&&x|. because filter takes a reference.

But consider this:

#[derive(Debug, Eq, PartialEq)]
struct Person {
    name: String,
    height_in_cm: i32,
    age: i32,
}


fn main() {

    let mut people: Vec<Person> = Vec::new();
    people.push(Person{name: "John".to_string(), height_in_cm: 180, age: 60});
    people.push(Person{name: "Carmen".to_string(), height_in_cm: 160, age: 30});
    people.push(Person{name: "Maria".to_string(), height_in_cm: 171, age: 25});

    let more_than_170 = people.iter().
        filter( | person | person.height_in_cm > 170).
        collect::<Vec<&Person>>();

    println!("more than 170:{:?}", more_than_170);
}

Here “person” does not take any “&&” inside the closure argument or “**” inside the filter predicate.

Why is that? Am I missing something trivial?

Markus


#2

Field access performs automatic dereferencing. From The Rust Reference:

if the type of the expression to the left of the dot is a
pointer, it is automatically dereferenced as many times as necessary
to make the field access possible.


#3

Thanks, that is very helpful!