首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当使用structopt时,如何测试用户是否提供了选项,或者它是否来自默认值?

当使用structopt时,如何测试用户是否提供了选项,或者它是否来自默认值?
EN

Stack Overflow用户
提问于 2021-09-09 14:06:41
回答 1查看 136关注 0票数 0

我使用的是structopt板条箱,我有以下结构:

代码语言:javascript
复制
#[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?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-09 14:48:02

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

代码语言:javascript
复制
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的宏魔术)来检查lengthArgMatches::occurrences_of中出现的次数。然而,这并不是非常惯用的。

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69119698

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档