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)?
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.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With