Search code examples
rustclap

How do I allow muti-option flags in Clap?


For my RUST program, I am using Clap to parse my command line arguments. I want to let users input flags like so: usage: file [-bhLs] [FILE...] my current struct is

struct Args {
/// option for check
#[arg(default_value ="-h")]
option: String,

/// filename to check
#[arg(default_value ="")]
filename: String,   }

when I try ./file -b foo.txt it says

`error: Found argument '-b' which wasn't expected, or isn't valid in this context

If you tried to supply '-b' as a value rather than a flag, use '-- -b'

Usage: file [OPTION] [FILENAME]`

How can I fix this problem and allow muti-option flags like -bhL and -hLs?


Solution

  • Option flags are not defined with a specific parameter option. They are defined by the short and long attribute values.

    So for your example, you would actually write the code like this:

    #[derive(Parser)]
    struct Args {
        #[arg(short = 'b')]
        b_option: bool, // this will be `-b`
        #[arg(short)]
        n_option: bool, // this will be `-n`
    }
    

    I think you can only use such compound flags for boolean options, or at least, only for options that don't require a value to be given.