Ben Chuanlong Du's Blog

It is never too late to learn.

Parsing Command-line Arguments in Rust

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Tips and Traps

There are 2 popular crates clap and structopt (based on clap) for this purpose. I personally prefer clap .

In [3]:
:dep clap = "2.33.3"

Sub Commands

In [ ]:
use clap::{Arg, App, SubCommand};
In [ ]:
let args = App::new("ofcp")
    .subcommand(
        SubCommand::with_name("test")
        .about("Test score_r4")
        .arg(
            Arg::with_name("id2")
            .long("id2")
            .value_name("ID2")
            .takes_value(true)
            .help("Initial id2."))
        .arg(
            Arg::with_name("n2")
            .long("n2")
            .value_name("N2")
            .takes_value(true)
            .help("number to sample for row2."))
        .arg(
            Arg::with_name("n1")
            .long("n1")
            .value_name("N1")
            .takes_value(true)
            .help("number to sample for row1."))
        .arg(
            Arg::with_name("n0")
            .long("n0")
            .value_name("N0")
            .takes_value(true)
            .help("number to sample for row0."))
    ).get_matches();
In [ ]:
match args.subcommand() {
    ("test", Some(subm)) => {
        let time = SystemTime::now();
        let max_diff = test_score_r4(
        subm.value_of("id2").unwrap().parse::<u64>().unwrap(),
        subm.value_of("n2").unwrap().parse::<usize>().unwrap(),
        subm.value_of("n1").unwrap().parse::<usize>().unwrap(),
        subm.value_of("n0").unwrap().parse::<usize>().unwrap(),
        );
        println!("Time taken: {}, Max diff: {}", time.elapsed().unwrap().as_secs_f64(), max_diff);
    },
    (subcmd, _) => panic!("The sub command {} is not supported!", subcmd),
}

Comments