get - Return exact value in Rust Hashmap -
i can't find suitable way return exact value of key in hashmap in rust . existing get
methods return in different format rather exact format.
there 2 basic methods of obtaining value given key: get()
, get_mut()
. use first 1 if want read value, , second 1 if need modify value:
fn get(&self, k: &q) -> option<&v> fn get_mut(&mut self, k: &q) -> option<&mut v>
as can see signatures, both of these methods return option
rather direct value. reason there may no value associated given key:
use std::collections::hashmap; let mut map = hashmap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), some(&"a")); // key exists assert_eq!(map.get(&2), none); // key not exist
if sure map contains given key, can use unwrap()
value out of option:
assert_eq!(map.get(&1).unwrap(), &"a");
however, in general, better (and safer) consider case when key might not exist. example, may use pattern matching:
if let some(value) = map.get(&1) { assert_eq!(value, &"a"); } else { // there no value associated given key. }
Comments
Post a Comment