如何改变hash_map
的{{1}}条款中的None
(同样适用于match hash_map.get(...)
)?
vec.get
作为一个完整的例子,以下内容无法编译:
match hash_map.get(...) {
None => {
// How can I mutate hash_map here?
}
}
原因是map.get()
返回的use std::collections::HashMap;
fn map_question(map: &mut HashMap<String, String>) {
match map.get(&"foo".to_string()) {
Some(s) => {
// Do something with s
},
None => {
// I'd like to mutate `map` here, but I'm getting "cannot borrow map"
map.insert("bar".to_string(), "x".to_string());
}
}
}
仍在范围内,因此借用了Option<&String>
。这是完整的错误消息:
map
我的解决方案一直使用error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable
--> test.rs:10:13
|
4 | match map.get(&"foo".to_string()) {
| --- immutable borrow occurs here
...
10 | map.insert("bar".to_string(), "x".to_string());
| ^^^ mutable borrow occurs here
11 | }
12 | }
| - immutable borrow ends here
解决此问题:
if let
(请注意,我们此处未使用fn map_alternative(map: &mut HashMap<String, String>) {
if let Some(s) = map.get(&"foo".to_string()) {
// Do something with s
}
// Now we can mutate `map` because the `Option` return by `.get`
// is out of scope.
map.insert("bar".to_string(), "x".to_string());
}
子句,因为else
返回的Option<&String>
仍然在.get
子句的范围内某种原因。)
但这似乎有些令人不满意。我可以告诉Rust,当我与else
匹配时,我已经完成了从None
获得的Option
对象吗?