我尝试从一个向量中删除指定元素(如果该元素存在):
我接着得到:
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行右侧返回一个不可变的向量引用),但我不确定该如何解决它。如果尝试像这样做:
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
对我来说,这些错误似乎有些循环,这让我觉得需要重新思考我的设计。 我该如何解决此问题?
Vec :: retain
来简化position
/remove
的过程。 请参见根据某些条件从Vec中删除元素 - trentdrain_filter
(如果它返回任何项,则它们已被删除;否则,请打印消息),但在稳定版本中,这个答案可能是你最好的选择。 - trent