Closed. This question needs
debugging details。它当前不接受答案。
想改善这个问题吗?更新问题,以便将其作为
on-topic用于堆栈溢出。
在11个月前关闭。
Improve this question
fn update(&mut self, engine: &mut Engine, delta_time: f32){
let game_state_ref = engine.get_game_state();
let game_state = game_state_ref.borrow_mut();
for entity in game_state.get_entities() {
let ai_component = game_state.get_component_ai_mut(*entity).unwrap();
ai_component.update(delta_time)
}
}
编译器不会让我借用可变的
game_state
类型
Rc<RefCell<GameState>>
引用。是否有人对如何解决或解决此问题有想法?
error[E0502]: cannot borrow `game_state` as mutable because it is also borrowed as immutable
--> src/systems/ai_system.rs:27:32
|
26 | for entity in game_state.get_entities() {
| -------------------------
| |
| immutable borrow occurs here
| immutable borrow later used here
27 | let ai_component = game_state.get_component_ai_mut(*entity).unwrap();
| ^^^^^^^^^^ mutable borrow occurs here
您提供的上下文很少,但是我想您的GameState
,Entity
和AiComponent
看起来像:
struct Entity {
id: i32,
// ...
}
struct AiComponent {
// ...
}
impl AiComponent {
pub fn update(&mut self, delta_time: f64) {
// ...
}
}
struct GameState {
entities: Vec<Entity>,
entity_id_to_ai: HashMap<i32, AiComponent>,
}
impl GameState {
pub fn get_entities(&self) -> &[Entity] {
&self.entities[..]
}
pub fn get_component_ai_mut(&mut self, entity: &Entity)
-> Option<&mut AiComponent>
{
self.entity_id_to_ai.get_mut(&entity.id)
}
}
使用此API,Rust将不允许您使用从相同
get_component_ai_mut
实例借来的
entity
调用
GameState
。为什么?因为有了
&mut self
,您可以合法地调用
self.entities.push(...)
甚至
self.entities.clear()
,这会使
entity
引用无效。
但看起来您不需要引用。考虑将您的API更改为:
impl GameState {
pub fn iter_ai_components_mut(&mut self)
-> impl Iterator<Item=&mut AiComponent>
{
self.entity_id_to_ai.values_mut()
}
}
然后,您可以执行以下操作:
for ai_component in game_state.iter_ai_components_mut() {
ai_component.update(delta_time);
}
我是一名优秀的程序员,十分优秀!