I am trying to convert a vector of &str
pairs into a HashMap
with the following code snippet:
use std::collections::HashMap;
fn main() {
let pairs = vec!(("foo", "bar"), ("toto", "tata"));
let map: HashMap<&str, &str> = pairs.iter().collect();
println!("{:?}", map);
}
However the compilation fails with this error:
<anon>:5:47: 5:56 error: the trait `core::iter::FromIterator<&(&str, &str)>` is not implemented for the type `std::collections::hash::map::HashMap<&str, &str>` [E0277]
<anon>:5 let map: HashMap<&str, &str> = pairs.iter().collect();
However if I add .cloned()
before calling collect()
everything works fine:
...
let map: HashMap<&str, &str> = pairs.iter().cloned().collect();
...
Even if I understand the error message (there is no implementation of the trait FromIterator<&(&str, &str)>
for the type HashMap<&str, &str>
) I do not understand where the type &(&str, &str)
comes from (according to the method signature in the Rust documentation) and why calling cloned()
fixes that problem.