【问题标题】:When using structopt, how to test if the user provided an option or if it comes from the default value?使用 structopt 时,如何测试用户是否提供了选项或是否来自默认值?
【发布时间】:2021-09-09 14:06:40
【问题描述】:

我正在使用structopt crate,我有以下结构:

#[derive(Clone, StructOpt, Debug)]
#[structopt(name = "test")]
pub struct CommandlineOptions {
    #[structopt(
    long = "length",
    help = "The length of the the string to generate",
    default_value = "50",
    index = 1
    )]
    pub length: usize,
}


let options = CommandlineOptions::from_args();

如果options.length50,我怎么知道它来自默认值50,还是用户提供的值50?

【问题讨论】:

  • 如果您想知道 (FWR),您可能应该使用 Option 并检查是否为 None

标签: rust structopt


【解决方案1】:

我认为structopt 无法做到这一点。解决此问题的惯用方法是使用Option<usize> 而不是usize(如文档中的here 所述):

use structopt::StructOpt;

#[derive(Clone, StructOpt, Debug)]
#[structopt(name = "test")]
pub struct CommandlineOptions {
    #[structopt(
    long = "length",
    help = "The length of the the string to generate",
    index = 1
    )]
    pub length: Option<usize>,
}

fn main() {
    let options = CommandlineOptions::from_args();
    println!("Length parameter was supplied: {}, length (with respect to default): {}", options.length.is_some(), options.length.unwrap_or(50));
}

如果这对您的情况不起作用,您也可以直接使用clap::ArgMatches 结构(structopt 只不过是clap 周围的宏魔法)来检查length 的出现次数ArgMatches::occurrences_of。但是,这不是很地道。

use structopt::StructOpt;

#[derive(Clone, StructOpt, Debug)]
#[structopt(name = "test")]
pub struct CommandlineOptions {
    #[structopt(
    long = "length",
    help = "The length of the the string to generate",
    default_value = "50",
    index = 1
    )]
    pub length: usize,
}

fn main() {
    let matches = CommandlineOptions::clap().get_matches();
    let options = CommandlineOptions::from_clap(&matches);
    
    let length_was_supplied = match matches.occurrences_of("length") {
        0 => false,
        1 => true,
        other => panic!("Number of occurrences is neither 0 nor 1, but {}. This should never happen.", other)
    };
    
    println!("Length parameter was supplied: {}, length (with respect to default): {}", length_was_supplied, options.length);
}

【讨论】:

    猜你喜欢
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 2010-12-26
    • 2010-09-14
    • 1970-01-01
    相关资源
    最近更新 更多