To learn Rust, I have started to implement some of the Project Euler problems. Now I want to take the next step and create a console based user interface, which has the ability for running all or only specific problems. Another requirement is that the user should be able to pass optional parameters only to a specific problem.
My current solution is to have a Trait ProjectEulerProblem
that declares for example run()
. With that I can do something like this:
fn main() {
let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
let problems: Vec<Box<problems::ProjectEulerProblem>> = vec![
box problems::Problem1,
box problems::Problem2
];
match args.flag_problem {
Some(x) => println!("Result of problem: {} is {}", x, problems[x-1].run()),
None => println!("No problem number given.")
}
}
My question is, is there a way to get rid of the explicit problems
vector initialization, maybe by using macros? Alternative ideas for implementing my application like described above are also welcome.
You can use a macro with repetition to generate your list without having to type out the full path and name every time.
Note, you cannot simply use indices, because the
concat_idents
macro requires an identifier and numbers are not identifiers.concat_idents
is also only available on nightly. On stable you need to give the entire struct name:PlayPen