2017-03-15 88 views
3

默认情况下,布尔字段设置为false,但我希望它默认设置为true在Rust的docopt中默认情况下是否可以将布尔选项设置为'true'?

我试图在docopt描述中使用[default: true],但似乎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

你能解释一下如何设置这个值为false吗? –

+0

如果没有办法将它设置为'false',那么问题很容易解决:'const FLAG_AN_OPTION_WITH_DEFAULT_TRUE:bool = true;' – Shepmaster

+0

@Shepmaster Errm,问题是如果一个标志默认为true,那么就没办法为最终用户设置标志为false。因此,将标志默认为true是没有意义的。一个标志是(true)或不是(false)。 – BurntSushi5

回答

1

Docopt本身并没有提供一种方式来“禁止”标志,因此,如果一个标志默认为真---即使它不是由最终用户给出---那么该标志将不可能是false

1

author of the crate says it's not possible,所以这是你可以得到的答案的权威性。


作为替代,你可以把一个参数,默认为 “真”:

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 
} 

请记住,您可以在解析的参数结构上实现方法,使其更易于处理。

相关问题