相关疑难解决方法(0)

为什么HashMap :: get_mut()取得了该范围其余部分的地图所有权?

我有以下代码将一些值插入HashMap,然后将它们取回:

use std::collections::HashMap;

fn things() {
    let mut map = HashMap::new();
    map.insert(5, "thing");
    map.insert(4, "world");
    map.insert(1, "hello");
    let mut thing = map.remove(&5);
    let mut world = map.get_mut(&4);
    let mut hello = map.get_mut(&1);
}
Run Code Online (Sandbox Code Playgroud)

尝试编译此代码会出现以下错误:

error[E0499]: cannot borrow `map` as mutable more than once at a time
  --> src/main.rs:10:21
   |
9  |     let mut world = map.get_mut(&4);
   |                     --- first mutable borrow occurs here
10 |     let mut hello = map.get_mut(&1);
   |                     ^^^ second mutable borrow occurs here
11 | } …
Run Code Online (Sandbox Code Playgroud)

rust

8
推荐指数
1
解决办法
2037
查看次数

标签 统计

rust ×1