我试图迭代地导航递归数据结构,以便在特定位置插入元素。据我所知,这意味着获取对该结构根部的可变引用,并将其逐步替换为对其后继者的引用:
type Link = Option<Box<Node>>;
struct Node {
next: Link
}
struct Recursive {
root: Link
}
impl Recursive {
fn back(&mut self) -> &mut Link {
let mut anchor = &mut self.root;
while let Some(ref mut node) = *anchor {
anchor = &mut node.next;
}
anchor
}
}
然而,这个失败了:
error[E0499]: cannot borrow `anchor.0` as mutable more than once at a time
--> src/main.rs:14:24
|
14 | while let Some(ref mut node) = *anchor {
| ^^^^^^^^^^^^
| |
| second mutable borrow occurs here
| first mutable borrow occurs here
...
18 | }
| - first borrow ends here
error[E0506]: cannot assign to `anchor` because it is borrowed
--> src/main.rs:15:13
|
14 | while let Some(ref mut node) = *anchor {
| ------------ borrow of `anchor` occurs here
15 | anchor = &mut node.next;
| ^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `anchor` occurs here
error[E0499]: cannot borrow `*anchor` as mutable more than once at a time
--> src/main.rs:17:9
|
14 | while let Some(ref mut node) = *anchor {
| ------------ first mutable borrow occurs here
...
17 | anchor
| ^^^^^^ second mutable borrow occurs here
18 | }
| - first borrow ends here
这是有道理的,因为anchor
和node
都指向相同的结构,但在解构后,我实际上不再关心anchor
。
如何使用安全的Rust正确实现back()
?
anchor
有初始引用 2)tmp
从anchor
移动,这意味着anchor
不再是一个引用 3)tmp
可以安全地借用,因为它在循环迭代结束时被丢弃。 - Fabian Knorrelse
分支中忘记了anchor = tmp;
,然后rustc为此引发了一个错误...无论如何,是的,这个想法是当你借用anchor
时不能重新分配它,所以我们将引用转移到tmp
,然后借用tmp
来分配anchor
。 - Matthieu M.anchor
的is_some()
方法。我已经编辑了你的帖子。 - Fabian Knorrunwrap
,因为虽然它是安全的,但也是(潜在)崩溃的源头。 - Matthieu M.