如何有效地查找和插入HashMap?
Vec
Vec
match
:
use std::collections::HashMap;// This code doesn't compile.let mut map = HashMap::new();let key = "foo";let values: &Vec<isize> = match map.get(key) { Some(v) => v, None => { let default: Vec<isize> = Vec::new(); map.insert(key, default); &default }};
error[E0502]: cannot borrow `map` as mutable because it is also borrowed as immutable --> src/main.rs:11:13 | 7 | let values: &Vec<isize> = match map.get(key) { | --- immutable borrow occurs here ... 11 | map.insert(key, default); | ^^^ mutable borrow occurs here ... 15 | } | - immutable borrow ends here
map.contains_key
map.get
):
// This code does compile.let mut map = HashMap::new();let key = "foo";if !map.contains_key(key) { let default: Vec<isize> = Vec::new(); map.insert(key, default);}let values: &Vec<isize> = match map.get(key) { Some(v) => v, None => { panic!("impossiburu!"); }};
match
?
SMILET