【问题标题】:Rust loop on HashMap while borrowing self借用self时HashMap上的Rust循环
【发布时间】:2017-07-25 19:22:44
【问题描述】:

我有一个 Element 结构,它实现了一个更新方法,该方法需要一个滴答持续时间。该结构包含一个组件向量。允许这些组件在更新时修改元素。我在这里遇到借用错误,我不知道该怎么办。我尝试用一​​个块来修复它,但该块似乎不能满足借用检查器。

use std::collections::HashMap;
use std::time::Duration;

pub struct Element {
    pub id: String,
    components: HashMap<String, Box<Component>>,
}

pub trait Component {
    fn name(&self) -> String;
    fn update(&mut self, &mut Element, Duration) {}
}

impl Element {
    pub fn update(&mut self, tick: Duration) {
        let keys = {
            (&mut self.components).keys().clone()
        };
        for key in keys {
            let mut component = self.components.remove(key).unwrap();
            component.update(self, Duration::from_millis(0));
        }
    }
}

fn main() {}

错误

error[E0499]: cannot borrow `self.components` as mutable more than once at a time
  --> src/main.rs:20:33
   |
17 |             (&mut self.components).keys().clone()
   |                   --------------- first mutable borrow occurs here
...
20 |             let mut component = self.components.remove(key).unwrap();
   |                                 ^^^^^^^^^^^^^^^ second mutable borrow occurs here
...
23 |     }
   |     - first borrow ends here

error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> src/main.rs:21:30
   |
17 |             (&mut self.components).keys().clone()
   |                   --------------- first mutable borrow occurs here
...
21 |             component.update(self, Duration::from_millis(0));
   |                              ^^^^ second mutable borrow occurs here
22 |         }
23 |     }
   |     - first borrow ends here

【问题讨论】:

    标签: rust borrow-checker


    【解决方案1】:

    keys() method 在哈希图中的键上返回一个迭代器。 clone() 调用仅复制迭代器,而不复制键本身。您使用 map 函数的原始方法看起来很有希望。您可能需要使用collect() method of the iteratorVec 中收集结果:

    let keys = self.components.keys().cloned().collect::<Vec<_>>();
    

    然后:

    for key in keys {
        self.components.remove(&key).unwrap();
    }
    

    这可确保在删除操作开始之前复制所有密钥。

    【讨论】:

    • 感谢您的帮助。那成功了。我真的很感激??
    • 我会说self.components.keys().cloned().collect() 是首选。
    猜你喜欢
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 2022-12-01
    相关资源
    最近更新 更多