I would like to do the following:
- Find
Vec for a specific key and save it for future use. - If this does not exist, create an empty
Vec key for the key, but save it in a variable.
How to do it effectively? Naturally, I thought I could use match :
use std::collections::HashMap;
When I tried, he gave me errors like:
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
I ended up doing something similar, but I don’t like the fact that it searches twice ( map.contains_key and 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!"); } };
Is there a safe way to do this in just one match ?
hashmap lookup rust
Yusuke Shinyama Feb 14 '15 at 4:23 2015-02-14 04:23
source share