在迭代遞歸結構時無法獲得可變引用:一次不能以可變的形式多次借用我試圖迭代地導航遞歸數據結構,以便在某個位置插入元素。據我有限的理解,這意味著對結構的根進行可變的引用,并將其依次替換為對其追隨者的引用: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在摧毀它之后。怎么能back()是否正確地使用安全銹蝕來實現?
3 回答
慕運維8079593
TA貢獻1876條經驗 獲得超5個贊
anchor
保存對當前節點的引用的 另一個被分配給下一個節點的引用。
impl Recursive {
fn back(&mut self) -> &mut Link {
let mut anchor = &mut self.root;
loop {
let tmp = anchor;
if let Some(ref mut node) = *tmp {
anchor = &mut node.next;
} else {
anchor = tmp;
break;
}
}
anchor }}impl Recursive {
fn back(&mut self) -> &mut Link {
let mut anchor = &mut self.root;
loop {
match {anchor} {
&mut Some(ref mut node) => anchor = &mut node.next,
other => return other,
}
}
}}{anchor} 移動anchormatchanchoranchor
富國滬深
TA貢獻1790條經驗 獲得超9個贊
#![feature(nll)]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(node) = anchor {
anchor = &mut node.next;
}
anchor }}fn main() {}anchorif let
添加回答
舉報
0/150
提交
取消
