Search code examples
rusthashmap

Is there a way to consume a HashMap and get a vector of values in Rust?


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?


Solution

  • 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: