在尝试实现一个迭代器,它为链表的元素产生可变引用时,我偶然发现了一个奇怪的问题.
这很好用:
impl<'a, T> Iterator<&'a T> for LinkedListIterator<'a, T>{ fn next(&mut self) -> Option<&'a T> { match self.current { &Cell(ref x, ref xs) => {self.current = &**xs; Some(x)}, &End => None } } }
但这不起作用; 编译器说生命周期self
太短,无法保证其内容可以安全地重新借用:
impl<'a, T> Iterator<&'a mut T> for LinkedListMutIterator<'a, T>{ fn next(&mut self) -> Option<&'a mut T> { match self.current { &Cell(ref mut x, ref mut xs) => {self.current = &mut **xs; Some(x)}, &End => None } } }
我希望这两个例子都可以工作,或者两者都没有,但是我无法理解借用可变和不可变的东西会影响编译器检查生命周期的方式.当然,如果有足够长的东西可以安全借用,它的寿命足够长,可以安全地可靠地借用?
编辑:这是两个迭代器的定义:
pub struct LinkedListIterator<'a, T> current: &'a LinkedList} pub struct LinkedListMutIterator<'a, T> { current: &'a mut LinkedList }
LinkedLisk:
#[deriving(Eq, Clone)] pub enum LinkedList{ Cell(T, ~LinkedList ), End }
有关该文件的完整视图,请参阅https://github.com/TisButMe/rust-algo/blob/mut_iter/LinkedList/linked_list.rs