Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function only known at runtime

Tags:

rust

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?

like image 217
Chris Root Avatar asked May 30 '15 00:05

Chris Root


1 Answers

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

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.

like image 174
Shepmaster Avatar answered Sep 28 '22 09:09

Shepmaster