简体   繁体   English

在 hashmap 中存储 function

[英]Storing a function in a hashmap

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.我想将 function 存储在 rust 的 Hashmap 中,但我不知道如何“获取”它并在另一个位置调用它。 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?我想稍后“打电话”你好 function,有什么办法吗? or is there a alterative way to do this?还是有其他方法可以做到这一点?

HashMap.get returns Option<&Ihello> which means that the result could be either Some value Ihello or None (If the key does not exists). HashMap.get返回Option<&Ihello>这意味着结果可能是Some value IhelloNone (如果键不存在)。 So one solution is to destructure the Option using if let statement.因此,一种解决方案是使用if let语句来解构Option

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).您可以使用Box存储对 function 的引用,然后调用 function map.get(...).unwrap() ()()一行返回(注意)。

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()());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM