7

I'm implementing FromIterator for [MyStruct;4] where MyStruct is a small Copy struct. My current implementation is

fn from_iter<I: IntoIterator<Item=MyStruct>>(iter: I) -> Self {
    let mut retval = [Default::default();4];

    for (ret, src) in retval.iter_mut().zip(iter) {
        *ret = src;
    }

    retval
}

This works just fine, however I'm not sure that the for loop is as idiomatic as it could be. Is there perhaps a method like Slice::fill(iter) that could accomplish this more cleanly (and perhaps more efficiently)?

Inityx
  • 125
  • 1
  • 6
  • Maybe you can just use plain, old [map](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map)? – hellow Jul 06 '17 at 08:45

1 Answers1

1

Loops are OK and they generally optimize very well.

Another solution may be to collect() into an ArrayVec. It avoids having to fill the array with a default value first.

Kornel
  • 97,764
  • 37
  • 219
  • 309