Hi,
I have a function that handles commands on the command line. It gets in its input a (ordered) vector of function pointers, that are handlers for the messages. Then for each message, it tries to let each handler handle the message, until one succeeds. The function something like:
pub type Handler = fn(&str, &Vec<&str>) -> Option<i32>;
pub fn run_cli(handlers: Vec<Handler>) -> i32 {
let mut count: i32 = 0;
let stdin = io::stdin();
loop {
print!("[{}]: ", count);
io::stdout().flush().unwrap();
let cmd = stdin.lock().lines().next().unwrap().unwrap();
let mut cmd_iter = cmd.split_ascii_whitespace();
if let Some(cmd) = cmd_iter.next() {
match cmd {
"exit" => {
println!("Done!");
return 0;
}
_ => {
let args: Vec<&str> = cmd_iter.collect();
for handler in &handlers {
if let Some(_) = handler(cmd, &args) {
break;
}
}
}
}
}
count = count + 1;
}
}
This works fine if I have handlers that don't need any additional input. But now I have to write a handler that needs to get access to some external state. So I thought I could define it using curryng and closures. But a closure is not a function pointer.
Is there a way to either pass a list closures, or convert a closure to a fn pointer, or is there another idiomatic way to do this in Rust?