Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to execute a function with given name?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading