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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With