Lacrosse343
Lacrosse343

Reputation: 841

Is there a way to dynamically refer to a module and its functions in rust?

As I am completing Advent of Code 2021, I have a main.rs file that looks like this:

// # Day 1
    if day1::is_complete() && print_complete || !day1::is_complete() {
        day1::part1();
        day1::part2();
    } else {
        println!("✅ Day 1 finished!")
    }

    // # Day 2
    if day2::is_complete() && print_complete || !day2::is_complete() {
        day2::part1();
        day2::part2();
    } else {
        println!("✅ Day 2 finished!")
    }

...

This continues for all 25 days.

Every module has a function called part1 and part2.

Is there a way to do something like this for a more concise file like the python eval?

for day in 1..=25 {
   let mod_name = convert_to_mod_name(day);
   if mod_name::is_complete() && print_complete || !mod_name::is_complete() {
        mod_name::part1();
        mod_name::part2();
    } else {
        println!("✅ Day {day} finished!", day);
    }
   

Upvotes: 10

Views: 1398

Answers (1)

mcarton
mcarton

Reputation: 30001

Is there a way to do something like this for a more concise file like the python eval?

No. Python is a dynamic language. Rust is a statically compiled language.

The closest thing would be to load a dynamic link library. Rust doesn't have a stable ABI except for a small subset meant for FFI. That is inherently unsafe.

TL;DR: It's not worth for something like advent of code.

Upvotes: 4

Related Questions