I want my program to allow multiple occurrences of a flag. The flag isn't a vector, so action = ArgAction::Append doesn't work for me, and I want the last occurrence to take priority. I haven't found any way to do this yet.
struct Args {
/// Input files
files: Vec<String>
#[arg(short, long, default_value = "mystruct")]
flag: MyStruct
}
With my current code, running my_program --flag value1 --flag value2 raises an error:
error: the argument '--flag <FLAG>' cannot be used multiple times
Usage: my_program [OPTIONS] [FILES]...
For more information, try '--help'.
1 Like
You can use overrides_with.
#[derive(Parser, Debug)]
struct Args {
/// Input files
files: Vec<String>,
/// A flag that can be specified multiple times; last occurrence wins
#[arg(short, long, default_value = "mystruct", overrides_with = "flag")]
flag: MyStruct,
}
1 Like
Thanks! But is there a way not to repeat it for every argument? If not, that's okay.
1 Like
I am not sure if there is a way to set it globally, but I think using it on each field individually should work.
1 Like
There is args_override_self.
#[derive(Parser)]
#[command(args_override_self = true)]
struct Args {
/// Input files
files: Vec<String>
#[arg(short, long, default_value = "mystruct")]
flag: MyStruct
}
4 Likes