Storing a function in a hashmap

Viewed 434

I want to store a function inside a Hashmap in rust, but i dont know how to "get" it and call it at another location. Here's what ive tried

type Ihello = fn() -> String;


fn main() {
    use std::collections::HashMap;
    let mut mapp: HashMap<String, Ihello> = HashMap::new();
    mapp.insert(
        "hello".to_string(),
        hello
    );
    let hello_string = "hello".to_string();
    let hello: Option<&Ihello> = book_reviews.get(&hello_string);
    
}

fn hello() -> String {
    String::from("HELLOHELLOHELLO")
}

I want to "call" the hello function later on, is there any way to do it? or is there a alterative way to do this?

2 Answers

HashMap.get returns Option<&Ihello> which means that the result could be either Some value Ihello or None(If the key does not exists). So one solution is to destructure the Option using if let statement.

let hello: Option<&Ihello> = mapp.get(&hello_string);
if let Some(val) = hello {
    println!("{}", val()); // calling the function here
} else {
    println!("Key is missing!");
}

You can use a Box to store a reference to the function, then call the function that the map.get(...).unwrap() returns (notice we have ()() on the last line).

use std::collections::HashMap;

type Ihello = dyn Fn() -> String;

fn hello() -> String {
    "HELLO".to_string()
}

fn main() {
    let mut map: HashMap<&str, Box<Ihello>> = HashMap::new();
    
    map.insert("hello", Box::new(hello));
    
    println!("{}", map.get("hello").unwrap()());
}
Related