What is the best way to populate a fragment from an iterator in Rust?

I am implementing FromIterator for [MyStruct;4] , where MyStruct is a small copy of struct. My current implementation

 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 fine, but I'm not sure if the for loop is as idiomatic as it can be. Is there a way, like Slice::fill(iter) , that could do this more cleanly (and possibly more efficiently)?

+5
source share
1 answer

The loops are fine, and they are generally optimized very well.

Another solution might be collect() in ArrayVec . It avoids having to fill the array with the default value first.

+1
source

Source: https://habr.com/ru/post/1269542/


All Articles