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

前端 未结 2 1385
北恋
北恋 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: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_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.

提交回复
热议问题