Skip to content

Constructing a simple HashSet<char> requires RandomState type annotation #101319

Open
@hkBst

Description

@hkBst

I tried this code:

pub fn is_pangram(sentence: &str) -> bool {
    let mut letters = std::collections::HashSet::from_iter("abcdefghijklmnopqrstuvwxyz".chars());
    sentence.to_lowercase().chars().any(|c| {
        letters.remove(&c);
        letters.is_empty()
    })
}

I expected to see this code to compile, just like this code does:

pub fn is_pangram_bytes(sentence: &str) -> bool {
    let mut letters = std::collections::HashSet::from(*b"abcdefghijklmnopqrstuvwxyz");
    sentence.to_lowercase().bytes().any(|c| {
        letters.remove(&c);
        letters.is_empty()
    })
}

Instead, this happened:

error[[E0282]](https://doc.rust-lang.org/nightly/error-index.html#E0282): type annotations needed for `HashSet<char, S>`
 --> src/lib.rs:3:9
  |
3 |     let mut letters = std::collections::HashSet::from_iter("abcdefghijklmnopqrstuvwxyz".chars());
  |         ^^^^^^^^^^^
  |
help: consider giving `letters` an explicit type, where the type for type parameter `S` is specified
  |
3 |     let mut letters: HashSet<char, S> = std::collections::HashSet::from_iter("abcdefghijklmnopqrstuvwxyz".chars());
  |                    ++++++++++++++++++

I can fix it by including a type annotation for the RandomState:

pub fn is_pangram_with_randomstate_annotation(sentence: &str) -> bool {
    let mut letters: std::collections::HashSet<_, std::collections::hash_map::RandomState> =
        std::collections::HashSet::from_iter("abcdefghijklmnopqrstuvwxyz".chars());
    sentence.to_lowercase().chars().any(|c| {
        letters.remove(&c);
        letters.is_empty()
    })
}

But since

pub struct HashSet<T, S = RandomState>

I do not think I should need to do this.

Meta

rustc --version --verbose:

1.63.0 up to nightly 2022-08-31 9243168fa5615ec8ebe9 (tested on playground)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsD-confusingDiagnostics: Confusing error or lint that should be reworked.T-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