Skip to content

Instantly share code, notes, and snippets.

@sebastiandanconia
Last active September 25, 2023 05:47
Show Gist options
  • Save sebastiandanconia/803e024032f5a5d3f4bcc650201971c7 to your computer and use it in GitHub Desktop.
Save sebastiandanconia/803e024032f5a5d3f4bcc650201971c7 to your computer and use it in GitHub Desktop.
Parse CLI options in Rust - Basic Recipe
[package]
name = "getopt-toy"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
getopts = "0.2"
// Most of this is taken directly from https://docs.rs/getopts/latest/getopts/
extern crate getopts;
use getopts::Options;
use std::env;
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} FILE [options]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("o", "", "set output file name", "NAME");
opts.optflag("h", "help", "print this help menu");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!("{}", f.to_string()) }
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
let output = matches.opt_str("o");
let pp = if !matches.free.is_empty() {
matches.free[0].clone()
} else {
print_usage(&program, opts);
return;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment