在书中Learning Rust With Entirely Too Many Linked Lists:
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
self.next.map(|node| {
self.next = node.next.as_mut().map(|node| &mut **node);
&mut node.elem
})
}
}
src/second.rs:104:9: 104:13 error: cannot move out of borrowed content
src/second.rs:104 self.next.map(|node| {
^~~~
我无法理解为什么必须在 map()
之前调用 take()
. self.next
被移出来进行变异, take()
也移动了,对吗?
2 回答
重新阅读文章后,我想我得到了答案:
self.next.map
会将self.next
移动为值(进入您提供给map
的函数) . 但self
被借用为可变的 . 所以self.next
无法摆脱借来的self
. 解决问题的方法是首先self.next
拥有self.next
. 正确?我们来看看
take
的描述:因此,
take
不取得self.next
的所有权(不可能,因为self
仅被借用),而是取得self.next
内容的所有权,将其替换为有效内容 .请注意,这可以使用
std::mem::replace
函数来完成,该函数接受任何类型;take
只是Option
的糖 .