It is useful for functions to accept a dyn IntoIterator<blah>
object, which allows you to use into_iter()
, but that requires taking ownership of the collection.
It seems like Rust lacks a trait for the iter()
method. Does something like the itertools
crate provide a replacement?
Is there an trait for a resettable/restartable iterator?
Is there some alternative for a function that:
I guess I could take Iterator<Item=T>+Clone
, but that's a bit ugly (I'd have to use the iterator before using it the first time).
I should add my actual goal: I would like to make a bunch of functions that can take both &[T]
or &IndexSet<T>
(from indexmap crate) as arguments.
that requires taking ownership of the collection
No it does not, if the items can be references:
fn main() {
let a = vec![1, 2, 3];
do_it_twice_by_ref(&a);
dbg!(a);
}
fn do_it_twice_by_ref<'a>(it: impl IntoIterator<Item = &'a u8> + Copy) {
for i in it {
dbg!(i);
}
for i in it {
dbg!(i);
}
}
This works because usually there is also a impl IntoIterator for &Collection
(see here for IndexSet
) which is implemented using the iter
method.
And Copy
comes for free on shared references.