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.
Function notes. 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.
Finally 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}
A 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 24, 2023 (edit).