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