Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between 0..3 and [0, 1, 2].iter()

Tags:

rust

I can do this for a range type:

(0..3).collect::<Vec<i32>>();

But I can't do the same for:

[0, 1, 2].iter().collect::<Vec<i32>>();

With that I get:

 error: the trait `core::iter::FromIterator<&_>` is not implemented for the type `collections::vec::Vec<i32>` [E0277]

To avoid that error, I have to do:

[0, 1, 2].iter().map(|&x| x).collect::<Vec<i32>>();

Why is that so? I thought the two were a different way of doing the same thing.

like image 338
tshepang Avatar asked Dec 19 '22 07:12

tshepang


1 Answers

They're not the same thing.

The problem here is that the call to iter on the array produces an Iterator of &i32s. In order to work on every possible array, it can't return elements by value, since not all types implement Copy and you can't partially move out of an array. So, in order to collect into a Vec<i32>, you have to turn the &i32s into i32s by copying them.

The other way in which they're not the same: the range doesn't require there to be an array containing all elements somewhere. So there's that, too.

like image 177
DK. Avatar answered Dec 21 '22 20:12

DK.