以下代码有效...
let mut hash_map: HashMap<String, String> = HashMap::new();
let n1 = "n1".to_string();
let no1 = hash_map.entry(n1.clone()).or_insert(n1.clone());
no1.clear();
Run Code Online (Sandbox Code Playgroud)
但目前我向 HashMap 添加了第二个条目,它不再编译。那么,我需要更改什么才能将多个元素添加到 HashMap 中,并且之后仍然能够修改 HashMap 的元素呢?
let mut hash_map: HashMap<String, String> = HashMap::new();
let n1 = "n1".to_string();
let n2 = "n2".to_string();
let no1 = hash_map.entry(n1.clone()).or_insert(n1.clone());
let no2 = hash_map.entry(n2.clone()).or_insert(n2.clone());
no1.clear();
Run Code Online (Sandbox Code Playgroud)
上面的代码会导致以下编译错误:
error[E0499]: cannot borrow `hash_map` as mutable more than once at a time
--> src/main.rs:127:15
|
126 | let no1 = hash_map.entry(n1.clone()).or_insert(n1.clone());
| -------------------------- first mutable borrow occurs here
127 | let no2 = hash_map.entry(n2.clone()).or_insert(n2.clone());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
128 |
129 | no1.clear();
| ----------- first borrow later used here
Run Code Online (Sandbox Code Playgroud)
no1在您尝试插入第二个元素的行上在地图上保留可变借用。如果您想要确切的操作顺序,那么您无法在 中保留引用no1。您必须通过键重新获取引用:
let mut hash_map: HashMap<String, String> = HashMap::new();
let n1 = "n1".to_string();
let n2 = "n2".to_string();
hash_map.entry(n1.clone()).or_insert(n1.clone());
hash_map.entry(n2.clone()).or_insert(n2.clone());
hash_map.get_mut(&n1).expect("n1 present").clear();
Run Code Online (Sandbox Code Playgroud)
(游乐场)
持有对集合元素的引用对借用检查器的影响几乎与持有对整个集合的引用相同。
有一个原因。n2如果插入导致地图需要增长会发生什么?no1当值移动到新位置时,这将使引用无效。Rust 正在履行其职责并保护您免于执行内存不安全的操作。
| 归档时间: |
|
| 查看次数: |
488 次 |
| 最近记录: |