如何收集到数组中? [英] How do I collect into an array?

查看:39
本文介绍了如何收集到数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对枚举数组调用 .map():

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]>();
}

但编译器抱怨:

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]`

我该怎么做?

推荐答案

问题实际上在collect,而不是map.

The issue is actually in collect, not in map.

为了能够将迭代的结果收集到容器中,该容器应该实现FromIterator.

In order to be able to collect the results of an iteration into a container, this container should implement FromIterator.

<代码>[T;n] 没有实现 FromIterator 因为它一般不能这样做:产生一个 [T;n] 您需要准确地提供 n 元素,但是在使用 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.

还有一个你不会知道的困难,如果没有补充数据,你现在应该提供数组的哪个索引(以及它是空的还是满的)等等......这可以通过使用 来解决在 map 之后枚举(本质上是提供索引),但是如果提供的元素不足或太多,您仍然需要决定要做什么.

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.

因此,不仅目前不能在固定大小的数组上实现FromIterator;但即使在未来,这似乎也是一个远景.

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)],可能在宏的帮助下
  • 收集到不同的(可增长的)容器中,例如 Vec
  • ...

这篇关于如何收集到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆