Using defaults in clap

I'm using the clap crate to take commandline arguments. I have defined input:

                  .arg(Arg::with_name("input")
                        .short("i")
                        .long("input")
                        .value_name("INFILE")
                        .default_value( <INPUT> )
                        .help("Sets the input file name")
                        .takes_value(true))

But I would like the default if you don't give any swtiches that it uses the argument as the input file. So I'd like the user to be able to do something like:

myapp -i inputfile.txt -o output.txt or just myapp inputfile.txt to do the same thing.

the default output file works since I force the name, but how can I use as the default for input file ??

In the clap documentation, it gives an example of using value_of("arg").unwrap_or("default"), so you could do something like:

config.unwrap_or("input").unwrap_or("second argument")

Great, that worked. For anyone who comes across this question later I did:

                    .arg(Arg::with_name("INPUT")
                        .help("Sets the input file to use")
                        .required(true)
                        .index(1))
                    .arg(Arg::with_name("input")
                        .short("i")
                        .long("input")
                        .value_name("INFILE")
                        //.default_value( )
                        .help("Sets the input file name")
                        .takes_value(true))



println!("Using input file: {}", matches.value_of("input").unwrap_or_default());

Actually, that didn't do what I needed. Now it expects two input files. Changed to this and does what I expected.

println!("Using input file: {}", matches.value_of("input").unwrap_or(matches.value_of("INPUT").unwrap()));
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.