Skip to content

HashMap::from_iter doesn't compile without explicitly supplying the hasher #90879

Open
@hniksic

Description

@hniksic

Now that FromIterator is in the prelude, I expected to be able to create a HashMap like using HashMap::from_iter():

use std::collections::HashMap;
fn main() {
    let h = HashMap::from_iter([("foo", 1), ("bar", 2)]);
}

However, that doesn't compile, saying "type annotations needed for HashMap<&str, i32, S>":

 --> src/main.rs:3:13
  |
3 |     let h = HashMap::from_iter([("foo", 1), ("bar", 2)]);
  |         -   ^^^^^^^ cannot infer type for type parameter `S` declared on the struct `HashMap`
  |         |
  |         consider giving `h` the explicit type `HashMap<&str, i32, S>`, where the type parameter `S` is specified

Playground

I would expect <HashMap as FromIterator>::from_iter() to pick the default hasher in absence of an explicit request for a different one requested, like Vec::from_iter() compiles and defaults to the global allocator. (HashMap::from() also compiles, but it seems to be limited to the default hasher.)

Note that this is different from #69123 which is about a confusing diagnostic. This issue is about the error itself, in particular as compared to Vec::from_iter().

Tested with Rust 1.56.1 stable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceA-iteratorsArea: IteratorsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-libsRelevant to the library team, which will review and decide on the PR/issue.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions