使用StructOpt时如何判断选项值来自用户输入还是默认值?
How to Distinguish Between Default Value and User-Provided Value in StructOpt?
Problem Description
I'm using the structopt crate and defined the following struct:
#[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();
When options.length is 50, how can I tell if this value comes from the preset default or was actively provided by the user?
Solution
StructOpt itself doesn't track whether a value came from a default or user input directly in the parsed struct, but since it's built on top of clap, we can use clap's ArgMatches to check if the parameter was explicitly provided.
Here's a straightforward implementation:
- Retrieve the raw
ArgMatchesfrom the StructOpt-generated CLI app alongside parsing your options. - Use the
is_presentmethod onArgMatchesto verify if the parameter was explicitly set by the user.
Modified code example:
use structopt::StructOpt; #[derive(Clone, StructOpt, Debug)] #[structopt(name = "test")] pub struct CommandlineOptions { #[structopt( long = "length", help = "The length of the string to generate", default_value = "50", index = 1 )] pub length: usize, } fn main() { // Get raw argument matches from clap let matches = CommandlineOptions::clap().get_matches(); // Parse options as usual let options = CommandlineOptions::from_args(); // Check if "length" was explicitly provided by the user let is_length_provided = matches.is_present("length"); if is_length_provided { println!("Length was explicitly set to {} by the user", options.length); } else { println!("Length uses the default value of {}", options.length); } }
Key Notes:
matches.is_present("length")returnstruein both scenarios:- The user runs
test --length 50(explicit flag with value) - The user runs
test 50(sincelengthis a positional argument withindex=1)
- The user runs
- This works because
is_presentchecks if the parameter was encountered during parsing, regardless of the value. Even if the user inputs the exact same value as the default, it's still counted as explicitly provided.
内容的提问来源于stack exchange,提问作者Just a learner
相关产品推荐
相关产品推荐

