I was trying to create an example for dispatch tables. the first way, with a temporary mutable and calling insert works, but when I try to create table2 I get mismatched types error with some further details:
^ expected `HashMap<char, fn(i32, i32) -> i32>`, found `HashMap<char, fn(i32, i32) -> i32 {add}>`
Why is the difference?
use std::collections::HashMap;
fn add(x: i32, y: i32) -> i32 {
x + y
}
fn multiply(x: i32, y: i32) -> i32 {
x * y
}
fn main() {
let table = {
let mut table: HashMap<char, fn(i32, i32) -> i32> = HashMap::new();
table.insert('+', add);
table.insert('*', multiply);
table.insert('-', |x, y| x - y);
table.insert('/', |x, y| x / y);
table
};
let table2: HashMap<char, fn(i32, i32) -> i32> = HashMap::from([
('+', add),
('*', multiply),
('-', |x, y| x - y),
('/', |x, y| x / y),
]);
for op in ['+', '*', '-', '/'] {
let res = table[&op](8, 2);
println!("8 {op} 2 = {res}");
}
}