HashSet<K, V> has confusing errors thanks to lax BuildHasher bounds
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Code
use std::collections::*;
fn make_map() -> HashSet<String, String> {
Default::default()
}
fn main() {
let map = make_map();
// compiles!
for pair in &map {
}
// expected `String`, found `(_, _)`
for (k, v) in map {
}
}
Writing HashSet instead of HashMap does not cause immediate error, because HashSet is allowed to have two type arguments, and very few methods require it to have a specific type.
Current output
13 | for (k, v) in map {
| ^^^^^^ --- this is an iterator with items of type `String`
| |
| expected `String`, found `(_, _)`
Desired output
Ideally Rust should check early that the second type in HashSet is supposed to be a BuildHasher, and warn about that as soon as HashSet<_, InvalidType> is used.
Rationale and extra context
Lack of bound on HashSet itself + type inference make incorrect the type compile in many cases, producing either surprising behavior or confusing errors far away from the mistake.
Other cases
Similar to #87015
It's not possible to add actual trait bounds on HashSet, but maybe the compiler could be somehow informed that these bounds are always expected to be satisfied, and warn whenever they're not.
Rust Version
rustc 1.79.0-nightly (3c85e5624 2024-03-18)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the HashSet<String, String> example in the linked Playground and compare its behavior with the related #87015 issue. Identify where rustc could diagnose the invalid second type argument earlier; done means the compiler reports the expected BuildHasher constraint at the HashSet use rather than producing a distant iterator error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100