[英]Borrow vs mutable borrow strange failure in lifetimes
While trying to implement an iterator which yields mutable refs to elements of a linked list, I stumbled upon a strange issue. 在尝试实现一个迭代器,它为链表的元素产生可变引用时,我偶然发现了一个奇怪的问题。
This works fine: 这很好用:
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
}
}
}
But this doesn't work; 但这不起作用; the compiler says lifetime of
self
is too short to guarantee its contents can be safely reborrowed: 编译器说的终身
self
太短,以保证其内容可以安全地reborrowed:
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
}
}
}
I would expect that either both example work, or both do not, but I can't understand how borrowing something as mutable vs not-mutable would impact the way the compiler checks for lifetimes. 我希望这两个例子都可以工作,或者两者都没有,但是我无法理解借用可变和不可变的东西会影响编译器检查生命周期的方式。 Surely if something lives long enough to be safely borrowed, it lives long enough to be safely mutably borrowed?
当然,如果有足够长的东西可以安全借用,它的寿命足够长,可以安全地可靠地借用?
EDIT: Here is the definition of both Iterators: 编辑:这是两个迭代器的定义:
pub struct LinkedListIterator<'a, T>
current: &'a LinkedList<T>
}
pub struct LinkedListMutIterator<'a, T> {
current: &'a mut LinkedList<T>
}
LinkedLisk: LinkedLisk:
#[deriving(Eq, Clone)]
pub enum LinkedList<T> {
Cell(T, ~LinkedList<T>),
End
}
For a complete view of the file, please see https://github.com/TisButMe/rust-algo/blob/mut_iter/LinkedList/linked_list.rs 有关该文件的完整视图,请参阅https://github.com/TisButMe/rust-algo/blob/mut_iter/LinkedList/linked_list.rs
Note that you've left out the definition(s) of LinkedListMutIterator
for the two variant bits of code, which might be relevant to any real attempt to reproduce and dissect your problem. 请注意,您已经为代码的两个变
LinkedListMutIterator
省略了LinkedListMutIterator
的定义,这可能与任何重现和剖析问题的真实尝试相关。
So, I'll try to guess at what's going on. 所以,我会试着猜测发生了什么。
The compiler error message here might be misleading you; 这里的编译器错误消息可能会误导您; there are other factors beyond the lifetime of
self
that may be relevant here. 除了
self
的生命之外还有其他因素可能与此相关。
In particular I suspect the borrow-checker is complaining because it is trying to ensure that you are not creating multiple mutable-borrows that alias the same state. 特别是我怀疑借用检查器是在抱怨,因为它试图确保你没有创建多个可变借用的别名同一状态。
It is sound to have multiple immutable-borrows to the same piece of state... 对同一个州有多个不可改变的借口是合理的......
... but you cannot have multiple mutable-borrows to the same piece of state (because we want to ensure that if you have a &mut
reference to some state, then that reference is the only way to mutate the state). ...但是你不能有多个可变借用到同一个状态(因为我们想确保如果你有一个
&mut
引用某个状态,那么该引用是改变状态的唯一方法)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.