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

前端 未结 2 1380
北恋
北恋 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::>();
    

提交回复
热议问题