【发布时间】:2016-05-21 02:29:04
【问题描述】:
我是按照too many linked lists 来实现链表的。在尝试实现iter_mut()时,我自己做了,做了如下代码:
type Link<T> = Option<Box<Node<T>>>;
pub struct List<T> {
head: Link<T>,
}
struct Node<T> {
elem: T,
next: Link<T>,
}
impl<T> List<T> {
pub fn iter_mut(&mut self) -> IterMut<T> {
IterMut::<T>(&mut self.head)
}
}
pub struct IterMut<'a, T>(&'a mut Link<T>);
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next<'b>(&'b mut self) -> Option<&'a mut T> {
self.0.as_mut().map(|node| {
self.0 = &mut (**node).next;
&mut (**node).elem
})
}
}
我要避免强制和省略,因为明确可以让我理解更多。
错误:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/third.rs:24:16
|
24 | self.0.as_mut().map(|node| {
| ^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'b` as defined on the method body at 23:13...
--> src/third.rs:23:13
|
23 | fn next<'b>(&'b mut self) -> Option<&'a mut T> {
| ^^
note: ...so that reference does not outlive borrowed content
--> src/third.rs:24:9
|
24 | self.0.as_mut().map(|node| {
| ^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 20:6...
--> src/third.rs:20:6
|
20 | impl<'a, T> Iterator for IterMut<'a, T> {
| ^^
note: ...so that reference does not outlive borrowed content
--> src/third.rs:25:22
|
25 | self.0 = &mut (**node).next;
| ^^^^^^^^^^^^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0495`.
我看过Cannot infer an appropriate lifetime for autoref due to conflicting requirements。
我懂一点,但不多。我在这里面临的问题是,如果我尝试更改任何内容,则会弹出一个错误,提示无法匹配特征定义。
我的想法是,基本上我需要以某种方式声明生命周期 'b 比 'a 寿命更长,即 <'b : 'a> 但我不知道该怎么做。另外,我有类似的功能来实现iter(),效果很好。这让我很困惑为什么iter_mut() 会产生这样的错误。
迭代
type Link<T> = Option<Box<Node<T>>>;
pub struct Iter<'a, T>(&'a Link<T>);
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.0.as_ref().map(|node| {
self.0 = &((**node).next);
&((**node).elem)
})
}
}
impl<T> List<T> {
pub fn iter(&self) -> Iter<T> {
Iter::<T>(&self.head)
}
}
☝️这行得通。
【问题讨论】:
-
尚无答案,但这个问题与this one 几乎相同。
-
@SCappella,是的,这几乎是确切的一些问题。问题不在于编译代码。我主要对理解错误感兴趣。 @Vivek 的回答确实消除了一些疑问,并且链接问题的 cmets 也很有帮助,但仍然无法完全理解错误消息以及为什么同样适用于
iter()