我正在学习 Rust with Entirely Too Many Linked Lists并且有一个关于该书中初始链表的 drop 实现的问题。链表由堆栈分配的链接组成,该链接要么是空的,要么指向带有一些关联数据的堆分配的节点。
struct List {
head: Link,
}
enum Link {
Empty,
More(Box<Node>),
}
struct Node {
data: i32,
next: Link,
}
Run Code Online (Sandbox Code Playgroud)
书中给出的 drop trait 的实现std::mem::replace用于获取列表中节点的所有权。
// Copied from the book, omitting comments
impl Drop for List {
fn drop(&mut self) {
let mut cur_link = mem::replace(&mut self.head, Link::Empty);
while let Link::More(mut boxed_node) = cur_link {
cur_link = mem::replace(&mut boxed_node.next, Link::Empty);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我很困惑为什么这本书使用mem::replace来获得节点的下一个指针的所有权。似乎我们已经拥有boxed_node …
rust ×1