Sphere
Log in Join
☆ 8

type annotations needed error on collect into HashMap

rustc 1.78. I'm grouping a vec of records by a key:

let grouped = records.into_iter().fold(HashMap::new(), |mut acc, r| {
acc.entry(r.kind).or_default().push(r);
acc
});

Compiler says:

error[E0282]: type annotations needed
--> src/group.rs:21:18
|
21 | let grouped = records.into_iter().fold(HashMap::new(), |mut acc, r| {
| ^^^^^^^ consider giving grouped a type

I know the key is an enum and the value should be Vec<Record>. Why can't it infer that from the entry call?

⚑ Report

4 replies

☆ 0
P plastic ·2026-10-14#1

The or_default() makes the value type ambiguous until something constrains it. The closure body pushes into it, but inference doesn't always connect that back through fold's accumulator type. Annotate the map: let mut grouped: HashMap<Kind, Vec<Record>> = HashMap::new(); and use a plain loop, fold isn't buying you anything here.

⚑ Report
☆ 0
S soggy ·2026-10-14#2

Fair, a for loop is clearer than fold for this. Does the annotation still needed with a loop? I'd have thought push(r) pins the value type to Vec<Record>. I tried both versions and or_insert_with(Vec::new) does infer correctly, which I didn't expect. The fold version needed the explicit type exactly where the compiler pointed.

⚑ Report
☆ 0
B byte ·2026-10-19#3

A loop with or_default() can still be ambiguous for the same reason: or_default works for any Default type, so Rust needs the annotation to pick Vec. You can skip the annotation if you use or_insert_with(Vec::new) instead, which names the concrete type directly.

⚑ Report
☆ 0
G gremlin ·2026-10-25#4

Switched to a for loop with or_insert_with(Vec::new), no explicit annotation needed and it reads better. Good reminder that or_default trades inference clarity for brevity. That is the short version, anyway. Curious whether that holds up for you. I had to learn that one the hard way.

⚑ Report
Log in to reply.