迭代器的生命周期:fn next(&' mut self)

时间:2016-03-22 12:20:45

标签: iterator rust lifetime

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>)
}

错误:

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拥有LetterPersonLetter的可变借用转移到EditIterEditIter创建Mode借用Letter并发送它。如果您删除Iterator特征并按照错误消息中的说明执行操作,那么它可以正常工作,但这不会实现Iterator特征。

如何保存逻辑并修复错误?

1 个答案:

答案 0 :(得分:1)

由于您的Mode不需要任何可变参考,因此请从mut移除EditIter,它会起作用:

struct Person<T> {
    letter: Letter<T>,
}

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

struct EditIter<'a, T: 'a> {
    letter: &'a 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>),
}