首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有办法在锈蚀中改变借来的价值?

有没有办法在锈蚀中改变借来的价值?
EN

Stack Overflow用户
提问于 2020-04-13 11:54:01
回答 3查看 565关注 0票数 1
代码语言:javascript
复制
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>>引用借用为可变的。有没有人知道如何解决或解决这个问题?

代码语言:javascript
复制
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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-04-13 14:20:18

您提供的上下文非常少,但我想您的GameStateEntityAiComponent看起来如下:

代码语言:javascript
复制
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更改为:

代码语言:javascript
复制
impl GameState {
    pub fn iter_ai_components_mut(&mut self)
        -> impl Iterator<Item=&mut AiComponent>
    {
        self.entity_id_to_ai.values_mut()
    }
}

然后你就可以:

代码语言:javascript
复制
for ai_component in game_state.iter_ai_components_mut() {
    ai_component.update(delta_time);
}
票数 0
EN

Stack Overflow用户

发布于 2020-04-13 12:14:58

不像许多其他语言(例如。C++),Rust不会让您拥有共享状态和可更改性。你可以借用一些不可变的东西,你也可以变异你拥有的东西,但你不能把两者结合起来。

什么是所有权?

票数 0
EN

Stack Overflow用户

发布于 2020-04-13 13:14:43

有没有人知道怎么解决..。

你可以借很多次(X),也可以变一次。我建议你在编写复杂的程序之前,先阅读“锈书”,了解借贷的机制。好了!

参见:不能借入可变的,因为它也是不可变的借入

...or可以解决这个问题吗?

解决方法是在unsafe代码中取消引用原始指针,但除非没有其他方法,否则您应该避免这种情况。借用检查可能是为什么你想要使用锈开始!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61187332

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档