【发布时间】:2020-06-02 18:08:46
【问题描述】:
我正在尝试从向量中删除一个元素(如果它存在于其中):
use std::collections::HashMap;
fn test(map: HashMap<String, Vec<String>>, department: String, employee: String) {
let &mut list = map.get(&department).unwrap();
let index = list.iter().position(|x| x == &employee);
match index {
Some(i) => {
list.remove(i);
},
None => {
println!("No records of {} in {}!", &employee, &department);
},
}
}
我收到此错误:
error[E0308]: mismatched types
--> src/lib.rs:4:9
|
4 | let &mut list = map.get(&department).unwrap();
| ^^^^^^^^^ ----------------------------- this expression has type `&std::vec::Vec<std::string::String>`
| |
| types differ in mutability
|
= note: expected reference `&std::vec::Vec<std::string::String>`
found mutable reference `&mut _`
我以为我理解错误的含义(第 170 行的 RHS 返回对向量的不可变引用),但我不太确定如何解决它。如果尝试这样的事情:
let mut list = map.get(&department).unwrap();
let index = list.iter().position(|x| x == &employee);
match index {
Some(i) => {
list.remove(i);
},
...
}
然后我得到
error[E0596]: cannot borrow `*list` as mutable, as it is behind a `&` reference
--> src/lib.rs:8:13
|
4 | let mut list = map.get(&department).unwrap();
| -------- help: consider changing this to be a mutable reference: `&mut std::vec::Vec<std::string::String>`
...
8 | list.remove(i);
| ^^^^ `list` is a `&` reference, so the data it refers to cannot be borrowed as mutable
这些错误对我来说似乎是一种循环,这让我觉得我需要重新考虑我的设计。我该如何解决这个问题?
【问题讨论】:
标签: rust