An algorithm I wrote builds a temporary HashMap
. Once it's finished, I'm only interested in the values
of the hashmap, so I'd like to transfer ownership of the values from the HashMap<K, V>
to a Vec<V>
.
With a simplified example hashmap:
fn main() {
use std::collections::HashMap;
let mut h: HashMap<_, _> = HashMap::new();
h.insert(1, "foo".to_owned());
}
I can do:
let vals: Vec<&String> = h.values().collect();
- which is short and sweet, but the hashmap still owns the values;let vals: Vec<String> = h.values().cloned().collect()
(as in this question) - the result is what I need, but I was taught to avoid the extra clones;let vals: Vec<String> = h.into_iter().map(|(_k, v)| v).collect();
- does what I need without a clone, but is a bit ugly.
The actual values are a mid-sized struct ({String, Vec<String>}
, under a KB total).
Should I default to avoiding clone
in this case or is it premature optimization? Is there an idiomatic way to do this that I'm missing?