0

I would like to create a hashmap, where keys are strings and items are functions. I tried it like this:

use std::collections::HashMap;

fn print_one(x: i32) -> String {
    format!("One: {}", x)
}

fn print_two(x: i32) -> String {
    format!("Two: {}", x)
}

fn print_three(x: i32) -> String {
    format!("Three: {}", x)
}

fn main() {
    let function_map: HashMap<String, fn(i32) -> String> = HashMap::from([
        ("one".into(), print_one),
        ("two".into(), print_two),
        ("tree".into(), print_three)
    ]);
    
    println!("{}", function_map.get("one".into()).unwrap()(1));
    println!("{}", function_map.get("two".into()).unwrap()(1));
    println!("{}", function_map.get("tree".into()).unwrap()(1));
    
    println!("Done");
}

I get this error:

expected fn item, found a different fn item

It works like this if I use Vec, but for HashMap it gives me this error for some reason.

I've found a similar question with "expected fn item" error, but it did not help me understand how these functions could be stored in a hashmap

Iter Ator
  • 8,226
  • 20
  • 73
  • 164
  • 1
    casting the functions with `as fn(_) -> _` does seem to work: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=3bbbed6f56761c2e28f9395ee4e1c54e – Tobias S. Nov 10 '22 at 11:55
  • @TobiasS. Thanks, but why is that? – Iter Ator Nov 10 '22 at 11:56
  • 1
    Its pretty much explained in the question you linked. I only copied the solution from there. – Tobias S. Nov 10 '22 at 12:01
  • Hi @IterAtor, this is most possibly because of type inference. The compiler will first try to determine the type of the array that you have created and then match the `From` implementations on `HashMap`. – Deadbeef Nov 10 '22 at 12:08

0 Answers0