vec!() dereferencing when iterating with explicit type

  let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];

  let even_numbers: Vec<i32> = numbers.iter().filter(|&n| n % 2 == 0).map(|n| *n).collect();
    
  let even_numbers: Vec<_> = numbers.iter().filter(|&n| n % 2 == 0).map(|n| n).collect();

I am a newbie with rust. When the type is explicit i have to dereference but if i don’t state the type "the compiler knows and automatically picks the value"? Am i missing something, should not it be the other way around? I can not wrap my head around it. Please a bit explanation.

>Solution :

.iter() produces an iterator with an element type of &i32.

To collect into a Vec<i32>, you have to reference to copy the actual integer from the reference. That’s what .map(|n| *n) does. (BTW .copied() exists for this purpose).

The Vec<_> tells the compiler "I just want a vector, but infer the element type" so it does just that and picks the element type from the iterator: &i32.

You can instead use .into_iter() on the original Vec, which will consume the vector and return an iterator of owned (not references) elements (i32) directly.

Leave a Reply