Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
hkBst opened this issue Sep 2, 2022 · 5 comments
Open

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

hkBst opened this issue Sep 2, 2022 · 5 comments
Labels
A-diagnostics Area: Messages for errors, warnings, and lints D-confusing Diagnostics: Confusing error or lint that should be reworked. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Comments

@hkBst
Copy link
Contributor

hkBst commented Sep 2, 2022

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)
@hkBst hkBst added the C-bug Category: This is a bug. label Sep 2, 2022
@SkiFire13
Copy link
Contributor

When just HashSet is used it means to infer HashSet<T, S>, i.e. the S is also inferred. Default generic types are not used when doing inference. If you want to have the T inferred but not anything else then you can specify _ as its type, like so:

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()
    })
}

That said, it would be nice if default generic types played some role in type inference since most of the time they are the correct answer.

As to why from_iter throws and error and from doesn't, that's because FromIterator is implemented for HashSet<T, S> for any S, while From is implemented for just HashSet<T>.

@hkBst
Copy link
Contributor Author

hkBst commented Sep 2, 2022

@SkiFire13, thanks for the explanation and for the workaround; HashSet::<_> is a lot more acceptable than HashSet::<_, std::collections::hash_map::RandomState>.

Apparently by doing HashSet::<_> you assert that the unmentioned parameters have their default value, whereas if you do not mention any type parameters at all, then defaults are ignored and so all type parameters must be inferred from other information. Both cases seem very similar from a code perspective, especially if you are not aware of the default type parameters. It would also imply that introducing new default type parameters could break old code, which seems counterintuitive.

@SkiFire13
Copy link
Contributor

It would also imply that introducing new default type parameters could break old code, which seems counterintuitive.

Not exactly, to break code you also need to change the existing impls to also be generic over the new generic parameter, and that's generally regarded as a breaking change.

@BGR360
Copy link
Contributor

BGR360 commented Sep 12, 2022

Removing the bug label since it's not a compiler bug but rather a limitation of type parameter defaults, as @SkiFire13 mentioned. We could probably do something to improve the diagnostics, though. Like if the type parameter that the user needs to annotate is known to have a default, we could make the diagnostic give a better hint about that.

@rustbot label -C-bug +D-confusing +A-diagnostics

@rustbot rustbot added A-diagnostics Area: Messages for errors, warnings, and lints D-confusing Diagnostics: Confusing error or lint that should be reworked. and removed C-bug Category: This is a bug. labels Sep 12, 2022
@Noratrieb Noratrieb added the T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. label Apr 5, 2023
@estebank
Copy link
Contributor

Current output:

error[E0283]: type annotations needed for `HashSet<char, S>`
 --> src/lib.rs:2:9
  |
2 |     let mut letters = std::collections::HashSet::from_iter("abcdefghijklmnopqrstuvwxyz".chars());
  |         ^^^^^^^^^^^   ------------------------- type must be known at this point
  |
  = note: cannot satisfy `_: BuildHasher`
  = help: the following types implement trait `BuildHasher`:
            RandomState
            BuildHasherDefault<H>
  = note: required for `HashSet<char, _>` to implement `FromIterator<char>`
help: consider giving `letters` an explicit type, where the type for type parameter `S` is specified
  |
2 |     let mut letters: HashSet<char, S> = std::collections::HashSet::from_iter("abcdefghijklmnopqrstuvwxyz".chars());
  |                    ++++++++++++++++++

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-diagnostics Area: Messages for errors, warnings, and lints D-confusing Diagnostics: Confusing error or lint that should be reworked. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

No branches or pull requests

6 participants