Lifetime in Iterator: fn next(&'a mut self)

Viewed 159
struct Person<T> {
    letter: Letter<T>
}

struct Letter<T> {
    words: [Option<T>; 5]
}

struct EditIter<'a, T: 'a> {
    letter: &'a mut Letter<T>
}
impl<'a, T: 'a> Iterator for EditIter<'a, T> {
    type Item = Mode<'a, T>;
    fn next(&mut self) -> Option<Self::Item> {
        /* ... */
        Some(Mode::Editing(self.letter))
    }
}

enum Mode<'a, T: 'a> {
    Editing(&'a Letter<T>),
    Speaking(&'a Letter<T>)
}

Error:

src/temp.rs:16:28: 16:39 error: cannot infer an appropriate lifetime for automatic coercion due to conflicting requirements [E0495]
src/temp.rs:16         Some(Mode::Editing(self.letter))
                                          ^~~~~~~~~~~
src/temp.rs:14:5: 17:6 help: consider using an explicit lifetime parameter as shown: fn next(&'a mut self) -> Option<Self::Item>
src/temp.rs:14     fn next(&mut self) -> Option<Self::Item> {
src/temp.rs:15         /* ... */
src/temp.rs:16         Some(Mode::Editing(self.letter))
src/temp.rs:17     }

Person owns the Letter, Person transfers a mutable borrow of Letter to EditIter, EditIter creates a Mode with the borrowed Letter and sends it. If you remove the Iterator trait and do as written in the error message, it works, but this would not implement the Iterator trait.

How can I save the logic and fix the error?

1 Answers
Related