Calling a function only known at runtime

I want to make my first attempt in a Rust application by running an input validation server that can validate values ​​from an AJAX request. This means that I need a way to use the JSON configuration file to indicate which validation functions are used based on the name of the input values ​​and, possibly, the name of the form that appears at run time in the HTTP request. How can I do something similar to PHP call_user_function_array in Rust?

+4
source share
1 answer

You can add links to functions in 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 item in &input {
        let valid = match methods.get(item.0) {
            Some(f) => f(item.1),
            None => false,
        };

        println!("'{}' is a valid {}? {}", item.1, item.0, valid);
    }    
}

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

+8

All Articles