我正在尝试从头开始重新实现LinkedList
,我在IterMut
部分遇到了一些麻烦。我只是不会编译,我无法弄清楚原因。编译器只给我一条消息:
src/lib.rs:59:19: 59:27 error: cannot infer an appropriate lifetime for autoref due to conflicting requirements [E0495]
src/lib.rs:59 self.next.as_mut().map(|head| {
^~~~~~~~
src/lib.rs:58:5: 63:6 help: consider using an explicit lifetime parameter as shown: fn next(&'a mut self) -> Option<&'a mut A>
src/lib.rs:58 fn next(&mut self) -> Option<&'a mut A> {
src/lib.rs:59 self.next.as_mut().map(|head| {
src/lib.rs:60 self.next = &mut head.next;
src/lib.rs:61 &mut head.value
src/lib.rs:62 })
src/lib.rs:63 }
error: aborting due to previous error
Could not compile `linked_list`.
To learn more, run the command again with --verbose.
以下是实际代码:
use std::mem;
type Link<T> = Option<Box<Node<T>>>;
pub struct LinkedList<T> {
head: Link<T>,
length: usize,
}
struct Node<T> {
value: T,
next: Link<T>,
}
pub struct IterMut<'a, T: 'a> {
next: &'a mut Link<T>,
}
impl<T> Node<T> {
fn new(value: T) -> Node<T> {
Node {
value: value,
next: None
}
}
}
impl<T> LinkedList<T> {
pub fn new() -> LinkedList<T> {
LinkedList {
head: None,
length: 0,
}
}
pub fn push_front(&mut self, elem: T) {
let mut new_head = Box::new(Node::new(elem));
match self.head {
None => self.head = Some(new_head),
Some(ref mut head) => {
mem::swap(head, &mut new_head);
head.next = Some(new_head);
}
}
self.length += 1;
}
pub fn iter_mut(&mut self) -> IterMut<T> {
IterMut {
next: &mut self.head,
}
}
}
impl<'a, A> Iterator for IterMut<'a, A> {
type Item = &'a mut A;
fn next(&mut self) -> Option<&'a mut A> {
self.next.as_mut().map(|head| {
self.next = &mut head.next;
&mut head.value
})
}
}
#[cfg(test)]
mod tests {
use super::LinkedList;
#[test]
fn iter_mut() {
let mut list = LinkedList::new();
list.push_front(1);
list.push_front(2);
let mut iter = list.iter_mut();
assert_eq!(iter.next(), Some(&mut 2));
assert_eq!(iter.next(), Some(&mut 1));
assert_eq!(iter.next(), None);
}
}
修改
同样,我实施了Iter
。我天真地认为,IterMut
只需在适当的位置添加mut
即可。这是Iter
部分:
pub struct Iter<'a, T: 'a> {
next: &'a Link<T>,
}
impl<T> LinkedList<T> {
...
pub fn iter(&self) -> Iter<T> {
Iter {
next: &self.head,
}
}
...
}
impl<'a, A> Iterator for Iter<'a, A> {
type Item = &'a A;
fn next(&mut self) -> Option<&'a A> {
self.next.as_ref().map(|head| {
self.next = &head.next;
&head.value
})
}
}
为什么Iter
有效但IterMut
没有?