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.
They're not the same thing.
The problem here is that the call to iter
on the array produces an Iterator
of &i32
s. 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 &i32
s into i32
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With