为什么Option :: map在Iterator :: next的链表实现中取得所有权?

问题描述 投票:0回答:1

我想跟随Rust With Entirely Too Many Linked Lists

type Link<T> = Option<Box<Node<T>>>;

pub struct List<T> {
    head: Link<T>,
}

struct Node<T> {
    elem: T,
    next: Link<T>,
}

pub struct Iter<T> {
    next: Option<&Node<T>>,
}

implementing a iter

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        self.next.map(|node| {
            self.next = node.next.as_ref().map(|node| &**node);
            &node.elem
        })
    }
}

next方法中,map按值获取Option,因此它需要采用self.next,其恰好是Option<&Node<T>>类型的值。难道不会“偷”价值吗?

由于闭包是一个变异的,它不应该完全访问self并且这段代码不应该编译?我在这里错过了什么吗?

reference rust closures ownership-semantics
1个回答
1
投票

难道不会“偷”价值吗?

它会,但Option<&T>是可复制的。因此,self保留一份,map得到另一份。

需要完全访问self

由于该值被复制到map中,因此与self中的值无关。因此,self中的值可以在闭包内替换。

© www.soinside.com 2019 - 2024. All rights reserved.