エンティティシステム用のコードをゲームに書き込もうとしていますが、このエラーが発生しているので、同じことをするコードに煮詰めました。実際のコードでは同じエラーです。構造メソッドの借用エラーについて混乱しました
baz
が終了したときに、self.my_list
への参照が範囲外になることをコンパイラーが私に伝えている理由を理解できません。
私の錆のバージョンは、私はfor
ループが終了したとき、それはスコープの外に出ることを考えているだろうrustc 1.3.0 (9a92aaf19 2015-09-15)
のですか?
struct Foo {
name : &'static str,
}
struct Bar {
my_list : Vec<Foo>,
}
impl Bar {
fn New() -> Bar {
let mut new_instance = Bar { my_list : vec!() };
new_instance.my_list.push(Foo { name : "foo1" });
new_instance.my_list.push(Foo { name : "foo2" });
new_instance.my_list.push(Foo { name : "foo3" });
return new_instance;
}
fn Baz(&mut self, name : &'static str) -> Option<&Foo> {
for x in &self.my_list {
if x.name == name {
return Some(x);
}
}
self.my_list.push(Foo { name : "foo" });
return None;
}
}
fn main() {
let mut bar = Bar::New();
if let Some(x) = bar.Baz("foo1") {
println!("{} found", x.name);
}
}
これは私が取得エラーメッセージです:これは借りチェッカーの制限です
Compiling tutorial v0.1.0 (file:///C:/Code/Projects/rust/tutorial)
src\main.rs:35:9: 35:21 error: cannot borrow `self.my_list` as mutable because it is also borrowed as immutable
src\main.rs:35 self.my_list.push(Foo { name : "foo" });
^~~~~~~~~~~~
src\main.rs:29:19: 29:31 note: previous borrow of `self.my_list` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `self.my_list` until the borrow ends
src\main.rs:29 for x in &self.my_list {
^~~~~~~~~~~~
note: in expansion of for loop expansion
src\main.rs:29:9: 33:10 note: expansion site
src\main.rs:38:6: 38:6 note: previous borrow ends here
src\main.rs:28 fn Baz(&mut self, name : &'static str) -> Option<&Foo> {
...
src\main.rs:38 }
^
error: aborting due to previous error
Could not compile `tutorial`.
To learn more, run the command again with --verbose.
は... –
これは場合にのみ発生しますfor-loopで参照を返します。問題のMCVEはここにあります:http://is.gd/dJFkUz –
[desugared版](http://is.gd/atsegO)にも同じ問題があります。これは確かにバグのような気分です... – Shepmaster