Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a by-value iterator on the stack?

Tags:

iterator

rust

I can create a consuming iterator in the heap:

vec![1, 10, 100].into_iter()

I can also create an iterator on the stack that borrows the elements:

[1, 10, 100].iter()

But if I write this:

[1, 10, 100].into_iter()

This is not a consuming iterator because [T; _]::into_iter does not exist: IntoIterator is only implemented for the borrowed version (aka slice). Is there a simple way (preferably in the std lib) to create a consuming iterator on the stack?


I know that [1, 10, 100].iter().cloned() can be done, but this requires the items to be clonable.

like image 604
Boiethios Avatar asked Dec 17 '22 20:12

Boiethios


1 Answers

Is there a simple way (preferably in the std lib) to create a consuming iterator on the stack?

No.

Is there a simple way (preferably in the std lib) to create a consuming iterator on the stack?

Yes. Use a crate like stack or smallvec, which provide array types that implement IntoIterator.

like image 173
DK. Avatar answered Feb 04 '23 10:02

DK.