2017-03-15 3 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 자체 "가 비활성화"플래그, 플래그가 true로 디폴트 그래서 만약 ---에도로 그것은 최종 사용자가 제공하지 않습니다 --- 그러면 그 플래그는 이제까지 false이 될 수 없습니다.

1

author of the crate says it's not possible이므로 답변을 얻을 수있는 권한이 있습니다.


대안으로, 당신은 인수를 취할 수 "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 
} 

: 당신이 반대 논리가 플래그를 가질 수

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 
} 

또는 구문 분석 된 인수 구조체를 처리하기 쉽게 구현할 수 있다는 것을 기억하십시오.