How to Access Command Line Parameters in Rust

Created
Modified

Using std::env::args Function

This function actually returns the arguments that this program was started with. See the following example:

use std::env;

fn main() {
  for arg in env::args() {
    println!("{}", arg)
  }

  // to Vec
  let args: Vec<_> = env::args().collect();
  println!("{}", args[0])
}
hello-rust

The first element is traditionally the path of the executable, but it can be set to arbitrary text, and might not even exist. This means this property should not be relied upon for security purposes.

Using docopt Library

Installation

This crate is fully compatible with Cargo. Just add it to your Cargo.toml:

[dependencies]
#Using Serde's derive
serde = { version = "1.0", features = ["derive"] }

docopt = "1"

docopt Usage

Here is a full working example. Notice that you can specify the types of each of the named values in the Docopt usage string. Values will be automatically converted to those types (or an error will be reported).

use docopt::Docopt;
use serde::Deserialize;

const USAGE: &'static str = "
Usage: 
  hello-rust <x> [--name=<nm>]

Options:
--name=<nm>  Copy [default: Boo].
";

#[derive(Debug, Deserialize)]
struct Args {
  flag_name: String,
  arg_x: Option<i64>,
}

fn main() {
  let args: Args = Docopt::new(USAGE)
    .and_then(|d| d.deserialize())
    .unwrap_or_else(|e| e.exit());

  println!("{:?}", args.flag_name);
  println!("{:?}", args.arg_x);
}
"John"
Some(10)

Related Tags