一次不能多次借用可变的self.objects

时间:2018-06-27 05:44:59

标签: rust

我对以下代码有疑问:

use std::collections::HashMap;

struct SomeObject {}

enum SomeObjectWrapper<'a> {
    Wrap(&'a SomeObject),
}

struct SomeContainer {
    objects: HashMap<String, SomeObject>,
}

impl SomeContainer {
    fn new() -> SomeContainer {
        SomeContainer {
            objects: HashMap::new(),
        }
    }

    fn init(&mut self) -> () {
        let mut collected: Vec<SomeObjectWrapper> = Vec::new();

        for &string in vec!["this", "is", "a", "string"].iter() {
            // search for the artifact in the map
            let obj = self
                .objects
                .entry(string.to_owned())
                .or_insert(SomeObject {});

            let wrap = SomeObjectWrapper::Wrap(obj);
            collected.push(wrap);
        }

        // do something else with collected
    }
}

fn main() {
    let mut container = SomeContainer::new();
    container.init();
}

哪个会产生以下编译器错误:

error[E0499]: cannot borrow `self.objects` as mutable more than once at a time
  --> src/main.rs:25:23
   |
25 |               let obj = self
   |  _______________________^
26 | |                 .objects
   | |________________________^ mutable borrow starts here in previous iteration of loop
...
35 |       }
   |       - mutable borrow ends here

我看过有关此问题的类似文章,并尝试在循环内添加新作用域以删除可变引用,或尝试使用&*转换为不可变但无用。

我可以使该代码编译的唯一方法是注释掉该行:

collected.push(wrap);

我知道问题是.or_insert方法返回了我实际上不需要的可变借位,我可能应该停止使用entry方法,但这太方便了,我不会。在有人告诉我该代码无法修复之前,不要放弃!

0 个答案:

没有答案