【发布时间】:2020-05-07 19:23:17
【问题描述】:
我正在尝试根据同一个 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 所述。
如果我尝试插入或根据自身更新值,我可以使用入口API,如here所述。
我可以解决克隆问题,但我宁愿避免这种情况,因为在我的实际代码中检索到的值有些复杂。这需要不安全的代码吗?
【问题讨论】:
-
你在最后一行克隆了
some_val,所以你最好早点这样做——应该没什么区别。
标签: rust borrow-checker