Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to fill a slice from an iterator in Rust? [duplicate]

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)?

like image 723
Inityx Avatar asked Jul 06 '17 03:07

Inityx


People also ask

How do you eat an iterator in Rust?

fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. This method will evaluate the iterator until it returns None . While doing so, it keeps track of the current element.

Is iterator empty Rust?

You can make your iterator peekable and peek the first item; if it's None , then the iterator is empty. peek doesn't consume the item1, so the next call to next will return it.

How do you add slices in Rust?

As a result, you cannot use a Rust slice to insert, append or remove elements from the underlying container. Instead, you need either: to use a mutable reference to the container itself, to design a trait and use a mutable reference to said trait.

How do you copy an array in Rust?

In this article, we will see how to solve Copy An Array in rust code with examples. let arr =["a","b","c"]; // ES6 way const copy = [... arr]; // older method const copy = Array. from(arr);


1 Answers

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.

like image 173
Kornel Avatar answered Oct 08 '22 23:10

Kornel