问题
I am new to Rust and can not find the way of collecting the values of a hashmap into a vector in the documentation.
Let's say I have a hashmap:
score_table: HashMap<Id, Score>
and I want to get all the Score into a Vec
all_scores: Vec<Score>
I was tempted to use the values but it does not work since values is not a vec:
all_scores = score_table.values()
I know that Values implement the ExactSizeIterator trait, but I do not know how to collect all values of an iterator into a vector without manually writing a for loop and pushing the values in the vector one after one.
[edit 1]
I also tried to use std::iter::FromIterator; but landed to something like:
all_scores = Vec::from_iter(score_table.values());
expected type `std::vec::Vec<Score>`
found type `std::vec::Vec<&Score>`
[edit 2]
thanks to this question, I changed it to:
all_scores = Vec::from_iter(score_table.values().cloned());
and it does not produce errors to cargo check.
Is this a good way to do it?
回答1:
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>>();
来源:https://stackoverflow.com/questions/56724014/collect-values-of-a-hashmap-into-a-vector