rustiteratoriterablerust-itertools

Does rust have a trait for a collection with `iter()` method or a resettable iterator?


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:

  1. Wants to iterate over a collection several times without cloning it.
  2. Does not want to take ownership of anything.

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.


Solution

  • 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.