Return an optional iterator

Hello,
I would like to write something like:

pub fn lastv(&self) -> Option<impl Iterator<Item = &V>> {
    self.steps
        .iter()
        .filter_map(|(_, result)| match result {
            StepResult::VecVertexes(vertexes) => Some(vertexes),
            _ => None,
        })
        .last()
}

But I get the following error:

`&Vec<V>` is not an iterator
the trait `Iterator` is not implemented for `&Vec<V>`

I can't understand why this is not an iterator.
Also, since Option can be Iterator should it appear in the function signature?

Why do you not just return an Option<&Vec<V>>, or – even better – an Option<&[V]>?

The type &Vec<V> is not an iterator, but it is a collection type that you can iterate over, i.e. that you can convert into an iterator. The relevant trait is IntoIterator. (The same applies to Option.)

Something like -> Option<impl IntoIterator<Item = &V>> probably compiles, or to turn it into an iterator, you could add a call to .map(IntoIter::into_iter).

2 Likes

It is not an iterator because, well, it is not an iterator. It can be turned in to an iterator, but it is not an iterator. You could change your filter_map to return Some(vertexes.iter()) for example.

1 Like

Your repeated "not an iterator" implies that this is a FAQ. :slight_smile:

Perhaps we need to emphasize "container is not iterator" in Rust beginner's book.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.