Dynamically calling functions

I'm still a beginner with Rust so I was thinking about doing some Project Euler to build on my Rust experience. I was thinking about how to lay things out and it caused a bit of a thought experiment. I was trying to figure out how to run code dynamically in Rust. I suspect this will be much more difficult than in a higher level language but maybe there are already some thoughts about how to do it.

The correct way I can think to do it would be something like:

mod problems {
    pub fn one() {
        println!("one");
    }
    pub fn two() {
        println!("two");
    }
}

fn main() {
    let a = "one";
    match a {
        "all" => {
            problems::one();
            problems::two();
        }
        "one" => problems::one(),
        "two" => problems::two(),
        _ => {},
    }
}

but that will get a little cumbersome over time. I know this won't work but I'm trying to do something like:

mod problems {
    mod one {
        pub fn run() {
            println!("one");
        }
    }
    mod two {
        pub fn run() {
            println!("two");
        }
    }
}

fn main() {
    let torun = None;
    match torun {
        Some(x) => problems::x::run(),
        None => {        
            for problem in problems::* {
            problem.run();
        }}
    }

}

of course the modules would be in different files.

The I thought maybe I could learn to make macros and see if I could find some way to register all the functions somewhere. If I remember right there's also a build.rs file you can get cargo to run before building the other files. Maybe I could use that to build the match pattern for me in a module and then call it from main?

How would you go about it?

Take a look at fn and phf.

1 Like