root.parent.child.update(&mut root);
と書いてある部分で、おそらく update に root を渡しているせいで、所有権が移動(?)し、先頭の root がもう使えなくなっているようです。
これはどのように変更するとコンパイルできるようになるでしょうか?
各構造体はコピーせず、参照の状態で update に渡したいです。
該当のソースコード
Rust
1struct Root { 2 parent: Parent, 3 value: isize, 4} 5 6struct Parent { 7 child: Child, 8} 9 10struct Child { 11 value: isize, 12} 13 14impl Child { 15 fn update(&mut self, root: &mut Root) { 16 self.value += 1; 17 root.value += 1; 18 } 19} 20 21fn main() { 22 let mut root = Root { 23 value: 0, 24 parent: Parent { 25 child: Child { 26 value: 0, 27 }, 28 }, 29 }; 30 31 root.parent.child.update(&mut root); 32}
コンパイルエラーの内容
error[E0499]: cannot borrow `root.parent.child` as mutable more than once at a time --> examples/foo.rs:31:5 | 31 | root.parent.child.update(&mut root); | ^^^^^^^^^^^^^^^^^^------^---------^ | | | | | | | first mutable borrow occurs here | | first borrow later used by call | second mutable borrow occurs here error[E0499]: cannot borrow `root` as mutable more than once at a time --> examples/foo.rs:31:30 | 31 | root.parent.child.update(&mut root); | -------------------------^^^^^^^^^- | | | | | | | second mutable borrow occurs here | | first borrow later used by call | first mutable borrow occurs here For more information about this error, try `rustc --explain E0499`. error: could not compile `x` due to 2 previous errors
補足情報
rustc 1.58.1 (db9d1b20b 2022-01-20)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/04/18 23:00