我有以下代码,它将一些值插入到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);
}
尝试编译此代码将产生以下错误:
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 | }
| - first borrow ends here
在阅读了remove()
和get_mut()
方法的API文档后(幸运的是它们非常接近!),从方法签名中没有任何显著的原因可以说明为什么remove()
方法不会在当前作用域的其余时间内可变地借用映射,而get_mut()
方法会。
另一个让我感到困惑的数据片段是这段代码编译成功:
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);
map.get_mut(&4);
let mut hello = map.get_mut(&1);
}
不存储对get_mut()
的第一次调用结果不会导致地图在其余范围内被可变借用?我从文档中怎么能知道这一点呢?难道我还错过了其他什么吗?