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
拥有Letter
,Person
将Letter
的可变借用转移到EditIter
,EditIter
创建Mode
借用Letter
并发送它。如果您删除Iterator
特征并按照错误消息中的说明执行操作,那么它可以正常工作,但这不会实现Iterator
特征。
如何保存逻辑并修复错误?
答案 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>),
}