10

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Chris Root
  • 617
  • 6
  • 16

1 Answers1

15

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Ah nice so the reference to the function would be stored similar to how you might do so in Javascript. One part of the syntax I don't have a complete understanding of is what is between the angle brackets. I get that it makes certain at compile time that the values assigned to the hash are indeed function pointers but I can't find anything similar to that syntax in Rust examples in particular the `<_,` part. What is the signficance of the underscore in that syntax? – Chris Root May 30 '15 at 17:58
  • 3
    `_` tells the compiler to infer the type (in this case, `&str`) instead of having you to write it manually. See for more examples: http://is.gd/qiJUtJ – justinas May 31 '15 at 13:03
  • 1
    Okay thank you very much for the help. Makes me excited about building things in Rust. I have quite a few ideas. Being primarily a Ruby, PHP and Javascript coder this is a somewhat new world for me. – Chris Root Jun 01 '15 at 01:27