Clap basic
Parse command line arguments
This application describes the structure of its command-line interface usingclap
's builder style. Thedocumentation gives two other possible ways toinstantiate an application.
In the builder style, each possible argument is described by anArg
struct. The string given toArg::new()
is the internalname of the argument. Theshort
andlong
options control theflag the user will be expected to type; short flags look like-f
and longflags look like--file
.
Theget_one()
method is used to get an argument's value.It returnsSome(&
value)
if the argument was supplied bythe user, elseNone
.
The use ofPathBuf
is to allow file paths which are legalin Linux and MacOS, but not in Rust UTF-8 strings. This isbest practice: one encounters such paths quite rarely inpractice, but when it happens it is really frustratingwithout this.
use std::path::PathBuf;use clap::{Arg, Command, builder::PathBufValueParser};fn main() { let matches = Command::new("My Test Program") .version("0.1.0") .about("Teaches argument parsing") .arg(Arg::new("file") .short('f') .long("file") .help("A cool file") .value_parser(PathBufValueParser::default())) .arg(Arg::new("num") .short('n') .long("number") .help("Five less than your favorite number")) .get_matches(); let default_file = PathBuf::from("input.txt"); let myfile: &PathBuf = matches.get_one("file").unwrap_or(&default_file); println!("The file passed is: {}", myfile.display()); let num_str: Option<&String> = matches.get_one("num"); match num_str { None => println!("No idea what your favorite number is."), Some(s) => { let parsed: Result<i32, _> = s.parse(); match parsed { Ok(n) => println!("Your favorite number must be {}.", n + 5), Err(_) => println!("That's not a number! {}", s), } } }}
Usage information is generated byclap -h
. The usage forthe example application looks like this.
Teaches argument parsingUsage: clap-cookbook [OPTIONS]Options: -f, --file <file> A cool file -n, --number <num> Five less than your favorite number -h, --help Print help -V, --version Print version
We can test the application by running a command like the following.
$ cargo run -- -f myfile.txt -n 251
The output is:
The file passed is: myfile.txtYour favorite number must be 256.