Huy's Notes
Returning an Iterator

Returning an Iterator

#rust

There are a few way to return an iterator for a function, but the most straightforward and elegant way, in my opinion, is returning an impl:

fn some_itr(v: Vec<_>) -> impl Iterator<Item = String> {
  v.iter().map(|e| e.to_string())
}

Sometimes, you have to deal with lifetimes, so:

fn some_itr<'a>(v: &'a Vec<_>) -> impl Iterator<Item = String> + 'a {
  v.iter().map(|e| e.to_string())
}

Working with iterator is pretty neat, because you can control when will your code actually run (with collect()), especially when you have a large amount of data need to process.

Referred in


If you think this note resonated, be it positive or negative, please feel free to send me an email and we can talk.