Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) and the iter method usually is implemented in terms of it.
And Copy comes for free on shared references.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading