Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a new HashMap containing only elements accepted by the filter?

I’m trying this:

let map = HashMap::new();
map.insert(1, "foo");
map.insert(2, "bar");
let map2 = map.into_iter().filter(|k, v| k > 1).collect(); // doesn't compile
error[E0593]: closure is expected to take 1 argument, but it takes 2 arguments
 -->
  |
  | let map2 = map.into_iter().filter(|k, v| k > 1).collect(); // doesn't compile
  |                            ^^^^^^ ------ takes 2 arguments
  |                            |
  |                            expected closure that takes 1 argument

I need map2 to be a new map, not an iterator over map. What is the right way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are several problems. Here’s working code.

let mut map = HashMap::new();
map.insert(1, "foo");
map.insert(2, "bar");
let map2: HashMap<_, _> = map.into_iter().filter(|(k, v)| *k > 1).collect();
  1. map is not mutable. So you cannot insert element to map.
  2. For filter, the argument function must have only one argument. So instead of taking k and v as argument, take the tuple (k, v) as argument.
  3. When compiler can’t infer the collection type, you need to give a type when you use function collect.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading