gpt4 book ai didi

rust - 是否可以在 Rust 的 docopt 中默认将 bool 选项设置为 'true'?

转载 作者:行者123 更新时间:2023-11-29 08:00:27 24 4
gpt4 key购买 nike

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

我尝试在 docopt 描述中使用 [default: true],但似乎 default 不能应用于 bool 选项。我还尝试使用 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()
}
}

最佳答案

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
}

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

关于rust - 是否可以在 Rust 的 docopt 中默认将 bool 选项设置为 'true'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42803218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com