Hello Rust Folks,
I have been attempting to create a command-line application with Clap and I am having trouble implementing the creation of the Matches() struct with the usage of a function.
Context: I am fully able to create and utilise the clap application within main(). However, for the sake of test-ability, and the desire for a clean code base, I would like to make some sort of abstraction layer so i can create the clap application within tests without repeating the same instantiation commands over and over again.
Specifically, I can make it work when I do the specified example format:
fn main(){
let matches = App::new("example app").get_matches();
}
However, I really want to create something where I can simply call a function and return either the full app, or the matches.
fn make_app()->Matches{
let matches = App::new("example app").get_matches();
}
fn main(){
app = make_app()
}
Whenever I try the second variation, the compiler complains that the matches or app struct have temporary values that are dropped once the function is completed.
I know this has to do with lifetimes and the borrowing system. I've read the rust book chapter on this time and time again and I feel i understand what it's trying to say here. I understand that this is failing because matches is really a reference which dies at the end of the function.
But this leaves me with the question of how do I actually instantiate this outside of main? Is this where macros start coming in? Or is clap simply not designed to be instantiated outside of main and this means I need to start considering structopts to get the functionality i'm hoping for?
I can do structopts, but I just have the format built out nicely in YAML for the app and it feels like I should be able to abstract this part out without needing to rely on a completely different crate.
Thanks for your time and expertise.
Answer Found:
The problem I was running into was the implementation of the YAML API which could only use borrowed references, thus, making clean code implementations nearly impossible witout the usage of leak
.
As such, i just need to rebuild the app using something else.
Thank you to all of the great responses I recieved and for following up even after the original question evolved.