While getopts is available for the Rust platform, it is not very practical, since the generated map of properties must be checked for existence, then cast to the required types, leading to a lot of options and pattern matching.
With this library, you can define a structure representing the possible parameters, deriving Decodable, and parse it directly:
```Rust extern crate getopts; extern crate typedopts;
extern crate "rustc-serialize" as rustcserialize; use getopts::Options; use std::os; use typedopts::{DecodeResult,ErrorType}; use rustcserialize::Decodable;
struct Args { name: String, quantity: uint }
fn main() { let args = os::args(); let mut opts = Options::new(); opts.reqopt("n", "name", "insert a name here", ""); opts.reqopt("q", "quantity", "insert a quantity here", "");
let matches = match opts.parse(args.tail()) { Ok(m) => { m }, Err(f) => { println!("{}", f.toerrmsg()); return; } };
let result: DecodeResult
If the decode function finds the correct arguments and is able to parse them, you will get an instance of the structure you need in the Result. Otherwise, you receive an enum of errors:
Unless you want to handle the errors yourself, you can use directly the toerrmsg function.
Most types can be handled by the library, as long as they can derive from Decodable. Integers, Unsigned integers, floating point numbers, booleans, characters, strings are easy to do.
Enumerations will require that you define them as Decodable too:
```Rust
enum Color { red, green, blue }
pub struct ParseEnum { color: Color } /* ... / if(decoded.color == blue) { / ... */ } ```
Options are also supported:
```Rust
pub struct ParseOption {
option: Option
/* ... */ match decoded.option { Some(i) => println!("optional number is {}", i), None => println!("no number was provided") } ```
By default, if you define any options as required, getopts will need them everytime, even when you just want to display the help and usage instructions.
A way to fix it is available in the examples/getopt.rs file. Basically, you define a function to generate the getopts instance (trust me on this, it will avoid move problems):
```Rust extern crate getopts; extern crate typedopts; extern crate "rustc-serialize" as rustc_serialize;
use std::os; use getopts::Options; use typedopts::{DecodeResult,ErrorType}; use rustc_serialize::Decodable;
struct TestStruct1 {
data_int: u8,
maybe: Option
fn generate_options() -> Options { let mut opts = Options::new(); opts.reqopt("d", "data-int", "number", "NB"); opts.optopt("m", "maybe", "maybe number", ""); opts.optflag("h", "help", "print this help menu");
return opts; } ```
Then you define the usage function (from the getopts documentation):
Rust
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options]", program);
print!("{}", opts.usage(brief.as_slice()));
}
Then, in your argument parsing function, you will parse the options two times, one to detect the help argument, another one for the main arguments.
```Rust fn main() { let args = os::args(); let program = args[0].clone();
let mut helpopts = Options::new(); helpopts.optflag("h", "help", "print this help menu");
helpopts.parse(args.tail()).map(|m| { if m.optpresent("h") { printusage(program.asslice(), generate_options()); return; } });
let mut opts = generateoptions(); let matches = match opts.parse(args.tail()) { Ok(m) => { m } Err(f) => { println!("{}", f.toerr_msg()); return } };
if matches.optpresent("h") { printusage(program.as_slice(), opts); return; }
let result: typedopts::DecodeResult
If the help argument is found, show the help then return immediately, otherwise, parse arguments normally.