0

I've got a problem with lifetime specifiers in Rust. I have a type Foo that holds a vector of Strings. It should also implement the Iterator trait, returning objects that hold a reference to Strings in Foo.

see code example

What should the lifetime '? be? How can I tell the Rust compiler that this works? Or is this entirely impossible or against some of Rust's idioms? What would be the appropriate workaround?

Code example:

struct Foo {
    strings: Vec<String>,
}

impl Foo {
    fn new(strings: Vec<String>) -> Self {
        Self { strings }
    }
}

struct Bar<'a> {
    ref: &'a String,
}

impl Iterator for Foo {
    type Item = Bar<'?>;

    fn next(&mut self) -> Option<Self::Item> {
        todo!();
    }
}
E_net4
  • 27,810
  • 13
  • 101
  • 139
  • Consider questioning whether `Foo` is really expected to implement `Iterator` here. If it is just a collection mean to be iterable, `IntoIterator` would be a better trait. Alternatives: implement `IntoIterator` for `Foo` or `&Foo`; add a method which returns an iterator to the inner vector. – E_net4 Mar 07 '23 at 11:55

1 Answers1

0

As it seems, this is not possible in current rust and probably never will [1]. I only see the following workaround.

Create another struct FooIterator that implements Iterator instead of Foo itself and is returned by a Foo::iter() method. This seems to be the common practice.

[1] Create Iterator that yields references to its fields