0

我正在使用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,
}


let options = CommandlineOptions::from_args();

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

4

1 回答 1

2

我不认为有可能做到这一点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::ArgMatchesstruct (structopt只不过是宏魔术clap)来检查lengthwith的出现次数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-09-09T14:48:02.057 回答