HashMap
, vec
We often need to translate from one type to another, and this is one of the more difficult tasks at first. In Rust we can change from a HashMap
to a vector.
Sometimes finding a useful module is worth more than lots of looping code. With FromIterator
we can call from_iter
to translate an iterator from HashMap
.
HashMap
to vec
This code example goes from a HashMap
to 3 different kinds of vectors. We can place the keys, values, or both keys and values at once into a vector.
from_iter
and pass the result of iter()
called on the HashMap
. This is a vector containing both keys and values.str
references from the keys()
of the HashMap
. This is probably a common usage of from_iter
.HashMap
's values. We use (for the third time) a special formatting code to display it.use std::collections::HashMap; use std::iter::FromIterator; fn main() { let mut map = HashMap::new(); map.insert("cat", 800); map.insert("frog", 200); // Version 1: get vector of pairs. let vec1 = Vec::from_iter(map.iter()); println!("{:?}", vec1); // Version 2: get vector of keys. let vec2 = Vec::from_iter(map.keys()); println!("{:?}", vec2); // Version 3: get vector of values. let vec3 = Vec::from_iter(map.values()); println!("{:?}", vec3); }[("cat", 800), ("frog", 200)] ["cat", "frog"] [800, 200]
HashMap
One way we can go from a Vector
to a HashMap
is by using a simple for
-loop. This code benefits from being clear and direct, but is not particularly clever.
use std::collections::HashMap; fn main() { // Create vec of 2 strings. let animals = vec!["dog", "lizard"]; // Create empty HashMap. let mut map = HashMap::new(); // Add each animal from the vector to the HashMap. for animal in &animals { map.insert(animal, 1); } println!("{:?}", map); }{"dog": 1, "lizard": 1}
Conversion between types is paramount for program development. If we could not convert types, we could not do much. These examples help with HashMap
Rust conversions.