I can not find a way to collect the values of a HashMap
into a Vec
in the documentation. I have score_table: HashMap
The method Iterator.collect
is designed for this specific task. You're right in that you need .cloned()
if you want a vector of actual values instead of references (unless the stored type implements Copy
, like primitives), so the code looks like this:
all_scores = score_table.values().cloned().collect();
Internally, collect()
just uses FromIterator
, but it also infers the type of the output. Sometimes there isn't enough information to infer the type, so you may need to explicitly specify the type you want, like so:
all_scores = score_table.values().cloned().collect::<Vec<Score>>();
If you don't need score_table
anymore, you can transfer the ownership of Score
values to all_scores
by:
let all_scores: Vec<Score> = score_table.into_iter()
.map(|(_id, score)| score)
.collect();
This approach will be faster and consume less memory than the clone approach by @apetranzilla. It also supports any struct, not only structs that implement Clone
.