UP | HOME

Returning an iterator

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.

Date: 2019-06-17 Mon 00:00

Author: Huy Tran

Created: 2019-06-19 Wed 01:22