CLI - how to return clap type properly


#1

Hi,

I am currently playing with CLI for my first rust app and what I would like to do is to use clap library in the following way:

main.rs

extern crate clap;
mod cli;
use cli::*;


fn main() {

      let options = mycli();

}

cli.rs

   use clap::{Arg, App, SubCommand};
 
   pub fn mycli ()-> clap::ArgMatches  {   // obviously not correct

           matches = App::new("tool")
                      .version("0.01")
                      .author("Mick Jagger")
                      .about("My cool tool")
                      .arg(Arg::with_name("input")

          ...... // other stuff here

         matches
    }

bottom line is to outsource all cli parsing and checking into cli.rs (fn mycli()) and once all program logic regarding cli parsing is satisfied the object is returned to my main() function.

How would one achieve this correctly ?

thnx


#2

That should work.

In some more complex cases you may need to specify the return type as clap::ArgMatches<'static>. There’s a lifetime annotation on this type, and it should be 'static meaning it’s not a temporary borrow depending on something else that isn’t returned.


#3

You might try looking over the way that I separated out CLAP args for my fortune-telling app: https://github.com/Velfi/i-ching/tree/master/src/bin

let me know if you have any questions.