How do I collect the values of a HashMap into a vector?

前端 未结 2 1384
北恋
北恋 2021-01-18 02:32

I can not find a way to collect the values of a HashMap into a Vec in the documentation. I have score_table: HashMap

相关标签:
2条回答
  • 2021-01-18 03:23

    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>>();
    
    0 讨论(0)
  • 2021-01-18 03:27

    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.

    0 讨论(0)
提交回复
热议问题