7

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ishamael
  • 12,583
  • 4
  • 34
  • 52

1 Answers1

14

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    The example on the doc site is almost exactly this: https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#examples-29 – Kevin Anderson Jan 17 '20 at 20:56