There are two ways to get the value from a HashMap in Rust if we know the key. One of them is to access in with square brackets and the other one is to use the get method.
Access value using square brackets
This is how we access the value of the key "snake". This works.
let snake = &animal["snake"];
If we try to do the same with a key that does not exist we will get a run-time panic!
: no entry found for key
.
let turtle = &animal["turtle"];
So we commented out that part of the example.
We could protect our code from panic by first checking if the HashMap contains the key and only access it if the key exists as we did in that other example.
Access value using the get method
let value = animal.get(name);
This will return an Option that will either contain Some(value)
or it will contain None
.
There are plenty of ways to extract the value from such Option, in this example we use a match.
What if the value itself can be None?
In other programming languages (or at least in Perl and Python) there are similar ways to get the value of a hash or a dictionary respectively. They will
return undef
or None
both when the key is missing and when the key is there but the value itself is undef
or None
. In Rust we don't have that issue.
If the values of a HashMap can contain None
then all the other values must be in Some()
so when call get
we will get back an Option<Option<value>>
or an Option<None>
. So we just need to peal of another layer of Option.
This is what I was trying to show in the value_is_option
function at the end of the example.
The full code example
examples/hashmap/get-value-from-hashmap/src/main.rs
use std::collections::HashMap;
fn main() {
let mut animal = HashMap::new();
animal.insert(String::from("snake"), String::from("long"));
animal.insert(String::from("giraffe"), String::from("tall"));
animal.insert(String::from("elephant"), String::from("heavy"));
println!("{:#?}", animal);
let snake = &animal["snake"];
println!("snake: {snake}");
// panic: no entry found for key
// let turtle = &animal["turtle"];
// println!("turtle: {turtle}");
for name in ["turle", "snake"] {
let value = animal.get(name);
match value {
Some(val) => println!("The value of {name} is {val}"),
None => println!("The key {name} does not exist in the HashMap"),
}
}
value_is_option();
}
fn value_is_option() {
let phone = HashMap::from([
("Joe", Some("123")),
("Jane", None),
]);
let val = phone.get("Jane");
println!("{val:?}"); // Some(None)
let val = phone.get("Mary");
println!("{val:?}"); // None
}