Idiomatic way to iterate internal types?

Let's say I have an internal type Walrus, which I can iterate to get Poems. I can imagine implementing this in two different way:

Traits:

impl IntoIterator for Walrus {
  type Item = Poem;
  ...
}

impl<'a> IntoIterator for &'a Walrus {
  type Item = &'a Poem;
  ...
}

Methods:

impl Walrus {
    fn iter(&self)     -> impl Iterator<Item = &Poem> { ... }
    fn into_iter(self) -> impl Iterator<Item =  Poem> { ... }
}

Which one is preferable? For a proper library, I'd just do both, as that's what std is doing. However for internal things, I have a strong preference to sticking with only one option.

For internal use, option 2 seems simpler to me! It’s less code, and you don’t need to name (or worse, create) a type for the iterator. This is especially useful when you are just iterating over some internal data structure, maybe with some maps or filters thrown in. Implementing IntoIterator requires you to name those, which can be a pain.

It may perform better with impl Iterator if the effective type has already gone through the effort of overriding methods like fold (which you could do) or try_fold (which requires unstable Try). Some std iterators also employ specialization, which you can't do in stable rust.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.