我对Rust还是个新手,所以我不太确定如何正确地重构我的代码,使我想要做的事情成为可能。Here是我正在运行的代码的MCVE的链接。
本质上,我试图做的是迭代实体的向量,并从每个实体中获得一个操作。我不需要为该部分特别指定可变的borrow,但我确实需要在稍后的函数中将对self的可变引用传递到方法中,以执行返回的操作。
下面是我得到的确切的错误消息:
error[E0502]: cannot borrow `*self` as immutable because it is also borrowed as mutable
--> src/main.rs:16:72
|
16 | let action = self.entities[self.current_entity].get_action(self);
| ------------- ---------- ^^^^ immutable borrow occurs here
| | |
| | mutable borrow later used by call
| mutable borrow occurs here
error: aborting due to previous error我应该如何组织我的代码,以使我尝试做的事情成为可能?
发布于 2019-09-29 19:40:52
我将第16行从您的示例中分离出来,以解释(我认为)发生了什么:
例如,来自
let action = self.entities[self.current_entity].get_action(self);至:
let entity = &mut self.entities[self.current_entity];
let action = entity.get_action(self);在上面,entity可变地引用self (通过self.entities间接地)。因此,get_action不能修改self,因为它可能-特别是-更改self.entities,从而使引用entity无效。这是(安全的) Rust不允许的。
您可以尝试将Level拆分为entities和noentities。这允许您显式地指定Level的哪些部分实际上是可变引用的。(有关更新的示例,请参阅https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a8199f0bd4f8119f2ec1e79f9ebb542d。)
也就是说,你会有
struct LevelNoEntities {
current_entity: usize,
foo: i32,
}
struct Level {
entities: Vec<Entity>,
noentities: LevelNoEntities,
}然后,您现在将拥有以下内容:
let entity = &mut self.entities[self.noentities.current_entity];
let action = entity.get_action(&self.noentities);现在,entity只引用self.entities,您仍然可以传递noentities,因为编译器现在知道您可变地只引用Level的一部分。
https://stackoverflow.com/questions/58152490
复制相似问题