PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

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

 September 20, 2022     hashmap, rust     No comments   

Issue

I can not find a way to collect the values of a HashMap into a Vec in the documentation. I have score_table: HashMap<Id, Score> and I want to get all the Scores into all_scores: Vec<Score>.

I was tempted to use the values method (all_scores = score_table.values()), but it does not work since values is not a Vec.

I know that Values implements 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.

I also tried to use std::iter::FromIterator; but ended with something like:

all_scores = Vec::from_iter(score_table.values());
expected type `std::vec::Vec<Score>`
   found type `std::vec::Vec<&Score>`

Thanks to Hash map macro refuses to type-check, failing with a misleading (and seemingly buggy) error message?, 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?


Solution

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>>();


Answered By - apetranzilla
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing