是否可以将布尔选项设置为' true'默认情况下在Rust的docopt中?

时间:2017-03-15 07:11:35

标签: rust docopt

默认情况下,布尔字段设置为false,但我希望默认设置为true

我尝试在[default: true]描述中使用docopt,但似乎default无法应用于布尔选项。我也尝试使用Rust的Default特性 - 它也不起作用。

以下是一个最小的例子:

extern crate rustc_serialize;
extern crate docopt;

use docopt::Docopt;

const USAGE: &'static str = "
Hello World. 

Usage:
  helloworld [options]

Options:
  --an-option-with-default-true   This option should by default be true
";

#[derive(Debug, RustcDecodable)]
struct Args {
    flag_an_option_with_default_true: bool,
}

impl Args {
    pub fn init(str: &str) -> Args {
        Docopt::new(USAGE)
            .and_then(|d| d.argv(str.split_whitespace().into_iter()).parse())
            .unwrap_or_else(|e| e.exit())
            .decode()
            .unwrap()
    }
}

2 个答案:

答案 0 :(得分:1)

没有

Docopt本身没有提供一种“禁用”标志的方法,所以如果一个标志默认为真 - 即使它没有被最终用户给出 - 那么该标志就不可能false

答案 1 :(得分:1)

author of the crate says it's not possible,以便您可以获得答案的权威。

作为替代,您可以采用默认为" true"的参数:

const USAGE: &'static str = "
Hello World. 

Usage:
  helloworld [options]

Options:
  --an-option=<arg>   This option should by default be true [default: true].
";

#[derive(Debug, RustcDecodable)]
struct Args {
    flag_an_option: String,
}

impl Args {
    // ...

    fn an_option(&self) -> bool {
        self.flag_an_option == "true"
    }
}

fn main() {
    let a = Args::init("dummy");
    println!("{}", a.an_option()); // true

    let a = Args::init("dummy --an-option=false");
    println!("{}", a.an_option()); // false

    let a = Args::init("dummy --an-option=true");
    println!("{}", a.an_option()); // true
}

或者你可以有一个具有反逻辑的标志:

const USAGE: &'static str = "
Hello World. 

Usage:
  helloworld [options]

Options:
  --disable-an-option
";

#[derive(Debug, RustcDecodable)]
struct Args {
    flag_disable_an_option: bool,
}

impl Args {
    // ... 

    fn an_option(&self) -> bool {
        !self.flag_disable_an_option
    }
}

fn main() {
    let a = Args::init("dummy");
    println!("{}", a.an_option()); // true

    let a = Args::init("dummy --disable-an-option");
    println!("{}", a.an_option()); // false
}

请记住,您可以在解析的参数struct上实现方法,以便更容易处理。