HashMap type inference

In the code below, why does type inference need help in the case of from_iter and collect, but not for new?

use std::collections::HashMap;

fn main() {

    let data = [(1,1),
                (2,4),
                (3,9)];

    let mut new = HashMap::new();
    for (k,v) in data {
        new.insert(k,v);
    }

    let from_iter = HashMap::from_iter(data);

    let collect = data
        .into_iter()
        .collect::<HashMap<_, _, _>>();

}

This is an example of what's described in Defaults Affect Inference. The new function is only implemented for S = RandomState, but its FromIterator is implemented for any S hasher.

1 Like

As for collect(), it's generic in the return type, so that it can collect into any collection. It doesn't only produce a HashMap; you could make a Vec or VecDeque or BTreeMap etc. using collect(). It's just a syntactically more convenient equivalent to FromIterator::from_iter().

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.