I have multiple functions that all follow the same naming scheme:
fn function1() {
...
}
fn function2() {
...
}
fn function3() {
...
}
I would like to execute function1, function2 or function3 depending on a variable, without manually having to use pattern matching.
The following pattern matching has the expected behavior but requires to hardcode every single value:
fn execute() {
let function_number = 2;
match function_number {
1 => function1(),
2 => function2(),
3 => function3()
};
}
I would like instead to do something that would look like this:
fn execute() {
let function_number = "2";
call("function" + function_number);
}
>Solution :
Use this execute function to make it dynamic:
fn execute(function_number: &str) {
// Convert the function_number to an integer
let function_number: u32 = function_number.parse().expect("Invalid number");
// Define a vector of function pointers
let functions: Vec<fn()> = vec![function1, function2, function3];
// Check if the function_number is within the valid range
if function_number <= functions.len() as u32 {
functions[(function_number - 1) as usize]();
} else {
println!("Invalid function number");
}
}
In main function you can easily call this function
fn main() {
let fn_number = "2";
execute(fn_number);
}