Struct ArgvMap

Source
pub struct ArgvMap { /* private fields */ }
Expand description

A map containing matched values from command line arguments.

The keys are just as specified in Docopt: --flag for a long flag or -f for a short flag. (If -f is a synonym for --flag, then either key will work.) ARG or <arg> specify a positional argument and cmd specifies a command.

Implementations§

Source§

impl ArgvMap

Source

pub fn deserialize<'de, T: Deserialize<'de>>(self) -> Result<T, Error>

Tries to deserialize the map of values into a struct.

This method should always be called to deserialize a ArgvMap into a struct. All fields of the struct must map to a corresponding key in the ArgvMap. To this end, each member must have a special prefix corresponding to the different kinds of patterns in Docopt. There are three prefixes: flag_, arg_ and cmd_ which respectively correspond to short/long flags, positional arguments and commands.

If a Docopt item has a - in its name, then it is converted to an _.

§Example
use serde::Deserialize;

use docopt::Docopt;

const USAGE: &'static str = "
Usage: cargo [options] (build | test)
       cargo --help

Options: -v, --verbose
         -h, --help
";

#[derive(Deserialize)]
struct Args {
  cmd_build: bool,
  cmd_test: bool,
  flag_verbose: bool,
  flag_h: bool,
}

let argv = || vec!["cargo", "build", "-v"].into_iter();
let args: Args = Docopt::new(USAGE)
    .and_then(|d| d.argv(argv()).deserialize())
    .unwrap_or_else(|e| e.exit());
assert!(args.cmd_build && !args.cmd_test
        && args.flag_verbose && !args.flag_h);

Note that in the above example, flag_h is used but flag_help could also be used. (In fact, both could be used at the same time.)

In this example, only the bool type was used, but any type satisfying the Deserialize trait is valid.

Source

pub fn get_bool(&self, key: &str) -> bool

Finds the value corresponding to key and calls as_bool() on it. If the key does not exist, false is returned.

Examples found in repository?
examples/hashmap.rs (line 34)
22fn main() {
23    let version = "1.2.3".to_owned();
24    let args = Docopt::new(USAGE)
25                      .and_then(|dopt| dopt.version(Some(version)).parse())
26                      .unwrap_or_else(|e| e.exit());
27    println!("{:?}", args);
28
29    // You can conveniently access values with `get_{bool,count,str,vec}`
30    // functions. If the key doesn't exist (or if, e.g., you use `get_str` on
31    // a switch), then a sensible default value is returned.
32    println!("\nSome values:");
33    println!("  Speed: {}", args.get_str("--speed"));
34    println!("  Drifting? {}", args.get_bool("--drifting"));
35    println!("  Names: {:?}", args.get_vec("<name>"));
36    println!("  Command 'ship' invoked? {:?}", args.get_bool("ship"));
37}
Source

pub fn get_count(&self, key: &str) -> u64

Finds the value corresponding to key and calls as_count() on it. If the key does not exist, 0 is returned.

Source

pub fn get_str(&self, key: &str) -> &str

Finds the value corresponding to key and calls as_str() on it. If the key does not exist, "" is returned.

Examples found in repository?
examples/hashmap.rs (line 33)
22fn main() {
23    let version = "1.2.3".to_owned();
24    let args = Docopt::new(USAGE)
25                      .and_then(|dopt| dopt.version(Some(version)).parse())
26                      .unwrap_or_else(|e| e.exit());
27    println!("{:?}", args);
28
29    // You can conveniently access values with `get_{bool,count,str,vec}`
30    // functions. If the key doesn't exist (or if, e.g., you use `get_str` on
31    // a switch), then a sensible default value is returned.
32    println!("\nSome values:");
33    println!("  Speed: {}", args.get_str("--speed"));
34    println!("  Drifting? {}", args.get_bool("--drifting"));
35    println!("  Names: {:?}", args.get_vec("<name>"));
36    println!("  Command 'ship' invoked? {:?}", args.get_bool("ship"));
37}
Source

pub fn get_vec(&self, key: &str) -> Vec<&str>

Finds the value corresponding to key and calls as_vec() on it. If the key does not exist, vec!() is returned.

Examples found in repository?
examples/hashmap.rs (line 35)
22fn main() {
23    let version = "1.2.3".to_owned();
24    let args = Docopt::new(USAGE)
25                      .and_then(|dopt| dopt.version(Some(version)).parse())
26                      .unwrap_or_else(|e| e.exit());
27    println!("{:?}", args);
28
29    // You can conveniently access values with `get_{bool,count,str,vec}`
30    // functions. If the key doesn't exist (or if, e.g., you use `get_str` on
31    // a switch), then a sensible default value is returned.
32    println!("\nSome values:");
33    println!("  Speed: {}", args.get_str("--speed"));
34    println!("  Drifting? {}", args.get_bool("--drifting"));
35    println!("  Names: {:?}", args.get_vec("<name>"));
36    println!("  Command 'ship' invoked? {:?}", args.get_bool("ship"));
37}
Source

pub fn find(&self, key: &str) -> Option<&Value>

Return the raw value corresponding to some key.

key should be a string in the traditional Docopt format. e.g., <arg> or --flag.

Source

pub fn len(&self) -> usize

Return the number of values, not including synonyms.

Trait Implementations§

Source§

impl Clone for ArgvMap

Source§

fn clone(&self) -> ArgvMap

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ArgvMap

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.