External Publication
Visit Post

`alloc`-only `HashMap`?

Rust Internals [Unofficial] March 11, 2026
Source

JarredAllen:

new/with_capacity: I see no reason why we can't allow that for any S: Default instead,

That would break inference.

But hold on, how is the compiler inferring S in this snippet?

let mut my_map = HashMap::new();
my_map.insert("hello", "there");
println!("{:?}", my_map);

What possibly determines it? Well, we can find out the hard way by using HashMap::default instead:

let mut my_map = HashMap::default();
my_map.insert("hello", "there");
println!("{:?}", my_map);



error[E0282]: type annotations needed for `HashMap<&str, &str, S>`
--> src/main.rs:4:22
 |
4 |     let mut my_map = HashMap::default();
 |         ----------   ^^^^^^^ cannot infer type for type parameter `S` declared on the struct >`HashMap`
 |         |
 |         consider giving `my_map` the explicit type `HashMap<_, _, S>`, where the type parameter `S` is specified

YUP! HashMap::new hardcoding S = RandomState is load bearing. Any code that creates a short-lived HashMap as part of some algorithm would run into this horrible error about how S is unknown!

An alias is too transparent to help in the expression case on its own.

play.rust-lang.org

Rust Playground

A browser interface to the Rust compiler to experiment with the language

Discussion in the ATmosphere

Loading comments...