私は、反復的なデータ構造を反復的に特定の位置に要素を挿入するためにナビゲートしようとしています。私の限られた理解に、これは構造のルートへの変更可能な参照を取り、連続的にそのフォロワーを参照することによって、それを置き換える意味:再帰的構造を反復することによって可変参照を取得する
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()
は安全な錆を使用して正しく実装できますか?
すごいです!ここで何が起こっているのか分かります:1) 'アンカー'は初期のリファレンスを持っています2) 'アンカー'から 'tmp'が移動しました。これはアンカーがもうリファレンスではないことを意味します。3)' tmp'は安全ですループの反復が終わるとすぐに削除されてから借りたものです –
ここで最も素晴らしいのは、最初に 'else'ブランチの' anchor = tmp; 'を忘れてしまって、rustcがエラーを発生させたということです。とにかく、借用している間に 'anchor'を再割り当てすることはできないので、' tmp'への参照を移して、 'tmp'を借りて' anchor'を割り当てます。 –
これは、移動前に 'anchor'で' is_some() 'を呼び出すことができるので、実際にはかなり簡潔に書くことができます。あなたの投稿を編集しました。 –