调用仅在运行时已知的函数 [英] Calling a function only known at runtime

查看:57
本文介绍了调用仅在运行时已知的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想第一次尝试 Rust 应用程序,通过输入验证服务器来验证来自 AJAX 请求的值.这意味着我需要一种方法来使用 JSON 配置文件来根据输入值的名称以及可能在运行时在 HTTP 请求中输入的表单名称来指定使用哪些验证函数.如何在 Rust 中执行类似于 PHP 的 call_user_function_array 的操作?

I want to do my first try at a Rust application by doing an input validation server which can validate values from an AJAX request. This means I need a way to use a JSON configuration file to specify which validation functions are used based on the name of the input values and perhaps a form name which come in at runtime in an HTTP request. How can I do something similar to PHP's call_user_function_array in Rust?

推荐答案

您可以向 HashMap 添加对函数的引用:

You can add references to functions to a HashMap:

use std::collections::HashMap;

// Add appropriate logic
fn validate_str(_: &str) -> bool { true }
fn validate_bool(_: &str) -> bool { true }

fn main() {
    let mut methods: HashMap<_, fn(&str) -> bool> = HashMap::new();

    methods.insert("string", validate_str);
    methods.insert("boolean", validate_bool);

    let input = [("string", "alpha"), ("boolean", "beta")];

    for (kind, value) in &input {
        let valid = match methods.get(kind) {
            Some(f) => f(value),
            None => false,
        };

        println!("'{}' is a valid {}? {}", value, kind, valid);
    }
}

这里唯一棘手的部分是 let mut methods: HashMap<_, fn(&str) ->布尔>= HashMap::new().您需要定义该映射将具有函数 指针的值.每个函数都有自己独特的匿名类型,函数指针是在此之上的抽象.

The only tricky part here is the line let mut methods: HashMap<_, fn(&str) -> bool> = HashMap::new(). You need to define that that map will have values that are function pointers. Each function has its own unique, anonymous type, and function pointers are an abstraction on top of that.

这篇关于调用仅在运行时已知的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆