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?
>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();
mapis not mutable. So you cannot insert element tomap.- For filter, the argument function must have only one argument. So instead of taking
kandvas argument, take the tuple(k, v)as argument. - When compiler can’t infer the collection type, you need to give a type when you use function
collect.