Iterators for collections inside structs

What is the idiomatic way to expose an iterator for a collection that is embedded inside a struct? For example, I have a struct which has a bunch of helper functions to make it easier to access the data inside the actual collection.

I have an all func to return the underlying vector, so that the caller can do an iter() on it.

struct MyCollection {
    data: Vec<i32>,

impl MyCollection{
    pub fn get_by_some_calc1(&self, index: i32) -> i32 { ... }
    pub fn get_by_some_calc2(&self, index: i32) -> i32 { ... }
    pub fn all(&self) -> Vec<&i32> { }

for idx in my_collection.all().iter() {

Is there a better option to return an iterator, without returning the underlying data, or implementing a new iterator for each type?

pub fn all(&self) -> impl Iterator<Item=&i32> { }

-> impl Trait means this function returns some concrete type without indirection or dynamic dispatch, but the caller doesn't know anything about this concrete type except it implements this trait.

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