I want to call .map()
on an array of enums:
enum Foo { Value(i32), Nothing, } fn main() { let bar = [1, 2, 3]; let foos = bar.iter().map(|x| Foo::Value(*x)).collect::<[Foo; 3]>(); }
but the compiler complains:
error[E0277]: the trait bound `[Foo; 3]: std::iter::FromIterator<Foo>` is not satisfied --> src/main.rs:8:51 | 8 | let foos = bar.iter().map(|x| Foo::Value(*x)).collect::<[Foo; 3]>(); | ^^^^^^^ a collection of type `[Foo; 3]` cannot be built from an iterator over elements of type `Foo` | = help: the trait `std::iter::FromIterator<Foo>` is not implemented for `[Foo; 3]`
How do I do this?
In Java 8, we can use . toArray() to convert a Stream into an Array.
The issue is actually in collect
, not in map
.
In order to be able to collect the results of an iteration into a container, this container should implement FromIterator
.
[T; n]
does not implement FromIterator
because it cannot do so generally: to produce a [T; n]
you need to provide n
elements exactly, however when using FromIterator
you make no guarantee about the number of elements that will be fed into your type.
There is also the difficulty that you would not know, without supplementary data, which index of the array you should be feeding now (and whether it's empty or full), etc... this could be addressed by using enumerate
after map
(essentially feeding the index), but then you would still have the issue of deciding what to do if not enough or too many elements are supplied.
Therefore, not only at the moment one cannot implement FromIterator
on a fixed-size array; but even in the future it seems like a long shot.
So, now what to do? There are several possibilities:
[Value(1), Value(2), Value(3)]
, possibly with the help of a macroVec<Foo>
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