Function pointers in hashmap

You can cast it to a function pointer.

fn f() {}
static m : HashMap<&str, fn()> = {
    let mut t = HashMap::new();
    t.insert("p", f as f());
    t
};

However you will then run into trouble that HashMap cannot be created at compile time. To fix this, use lazy_static.

use std::collections::HashMap;
use lazy_static::lazy_static;

fn f() {}

lazy_static! {
    static ref MAP: HashMap<&'static str, fn()> = {
        let mut t = HashMap::new();
        t.insert("p", f as fn());
        t
    };
}

playground

1 Like