Convert 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.
Version 1 We use from_iter and pass the result of iter() called on the HashMap. This is a vector containing both keys and values.
Version 2 Here we just get a vector of str references from the keys() of the HashMap. This is probably a common usage of from_iter.
Version 3 We get a vector from the 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]
Convert to 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}
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.