首页 文章

在链表上创建可变迭代器时,无法移出借来的内容

提问于
浏览
0

在书中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 回答

  • 0

    重新阅读文章后,我想我得到了答案:

    self.next.map 会将 self.next 移动为值(进入您提供给 map 的函数) . 但 self 被借用为可变的 . 所以 self.next 无法摆脱借来的 self . 解决问题的方法是首先 self.next 拥有 self.next . 正确?

  • 0

    我们来看看 take 的描述:

    fn take(&mut self) - > Option <T>
    从该选项中取出值,在其位置留下None .

    因此, take 不取得 self.next 的所有权(不可能,因为 self 仅被借用),而是取得 self.next 内容的所有权,将其替换为有效内容 .

    请注意,这可以使用 std::mem::replace 函数来完成,该函数接受任何类型; take 只是 Option 的糖 .

相关问题