Expected Fn / fn, found [closure@...]

You need to nudge type inference a little here:

use std::collections::HashMap;

enum A {
    B,
    C,
}

fn donotwork() {
    let g: HashMap<u8, fn(A) -> A> = HashMap::from([(0u8, (|x: A| x) as _)]);
    let h: HashMap<u8, Box<dyn (Fn(A) -> A) + Sync>> = HashMap::from([(0, Box::new(|x: A| x) as _)]);
}

Playground.

See i.e. this topic for a similar issue I encountered when using collections with elements that need to be coerced:

or this topic:


BTW, I created a macro that makes it easy for you to create a hashmap with values that need to be coerced to a different type before you can store them: map_macro::hash_map_e :smile:. It uses the same trick with explicit coercion to "something" (the _ placeholder) under the hood.

3 Likes