Skip to content

Type inference on HashSet #94969

Open
Open
@Yuri6037

Description

@Yuri6037

I've recently used HashSet in one of my project and I had to explicitly state the full type when initializing because rust was unable to infer from what I inserted inside. I've replicated the exact problem on a simpler structure on the following playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=ca668a190a8de1e47b5505508b8fe419.

Basically the issue is when an if let Some(value) = hashset.get(&anitem) type inference completely falls apart and you must specify let mut set: HashSet<StructureType> = HashSet::new()even if you call set.insert(an_instance_of_structure_type).

The unofficial Rust IRC on Libera.chat hints this is a limitation of accessing items of a HashSet before inserting elements inside and is related to the Borrow trait. It does indeed work if the let binding is moved after the calls to insert.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-collectionsArea: `std::collections`A-diagnosticsArea: Messages for errors, warnings, and lintsA-inferenceArea: Type inferenceT-compilerRelevant to the compiler 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