Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading