I have a hashmap: HashMap<SomeKey, SomeValue>
and I want to consume the hashmap
and get all its values as a vector.
The way I do it right now is
let v: Vec<SomeValue> = hashmap.values().cloned().collect();
cloned
copies each value, but this construction doesn't consume the hashmap. I am OK with consuming the map.
Is there some way to get values without copying them?
In Rust, we can extract the keys and values from a HashMap using the iter() and keys() / get() / unwrap() functions. Note that iter() return all key-value pairs in arbitrary order.
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.
The concept of HashMap is present in almost all programming languages like Java, C++, Python, it has key-value pairs and through key, we can get values of the map. Keys are unique no duplicates allowed in the key but the value can be duplicated.
For example, in Rust, we can display the content of an Array, Tuple, HashMap (Map), or Vector without loops using the Debug trait. These three compound types, by default, implement the Debug trait.
Convert the entire HashMap
into an iterator and discard the keys:
use std::collections::HashMap;
fn only_values<K, V>(map: HashMap<K, V>) -> impl Iterator<Item = V> {
map.into_iter().map(|(_k, v)| v)
}
You can then do whatever you want with the iterator, including collecting it into a Vec<_>
.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With