Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I collect into an array?

Tags:

rust

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?

like image 648
rausch Avatar asked Nov 05 '14 12:11

rausch


People also ask

Can you convert Stream to an array?

In Java 8, we can use . toArray() to convert a Stream into an Array.


1 Answers

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:

  • inline the transformation at call site: [Value(1), Value(2), Value(3)], possibly with the help of a macro
  • collect into a different (growable) container, such as Vec<Foo>
  • ...
like image 102
Matthieu M. Avatar answered Nov 05 '22 06:11

Matthieu M.