基于同一Hashmap中的另一个值插入HashMap

问题描述 投票:0回答:1

我正在尝试基于同一HashMap中的另一个值向HashMap中插入一个值,如下所示:

use std::collections::HashMap;

fn main() {
    let mut some_map = HashMap::new();
    some_map.insert("a", 1);

    let some_val = some_map.get("a").unwrap();

    if *some_val != 2 {
        some_map.insert("b", *some_val);
    }
}

发出此警告:

warning: cannot borrow `some_map` as mutable because it is also borrowed as immutable
  --> src/main.rs:10:9
   |
7  |     let some_val = some_map.get("a").unwrap();
   |                    -------- immutable borrow occurs here
...
10 |         some_map.insert("b", *some_val);
   |         ^^^^^^^^             --------- immutable borrow later used here
   |         |
   |         mutable borrow occurs here
   |
   = note: `#[warn(mutable_borrow_reservation_conflict)]` on by default
   = warning: this borrowing pattern was not meant to be accepted, and may become a hard error in the future
   = note: for more information, see issue #59159 <https://github.com/rust-lang/rust/issues/59159>

如果我想尝试更新现有值,则可以使用内部变异和RefCell,如here所述。

如果我尝试插入根据itself更新值,则可以使用条目API,如here所述。

我可以解决克隆问题,但是我宁愿避免这种情况,因为实际代码中检索到的值有些复杂。这会需要不安全的代码吗?

rust borrow-checker
1个回答
0
投票

很难说出您要查找的是什么,但是在这种情况下,如果只需要检查值,然后在更新哈希图之前销毁借用的值。肮脏和丑陋的代码将是这样的:

fn main() {
    let mut some_map = HashMap::new();
    some_map.insert("a", 1);

    let is_ok = false;

    {
        let some_val = some_map.get("a").unwrap();
        is_ok = *some_val != 2;
    }

    if is_ok {
        some_map.insert("b", *some_val);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.