Function pointers in hashmap

I'm trying to create a hashmap that maps strings to function pointers:


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

But this code is giving me this error:

32 |     t
   |     ^ expected fn pointer, found fn item

How do I fix this code?

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

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.