I'm trying to define arguments in a Rust program using the clap
crate. I want to achieve the following behavior:
- Users can either provide individual coefficients (
a
,b
, andc
) for a quadratic equation or a single argument containing the entire mathematical expression. - I've tried using
conflicts_with
on the individual coefficient arguments to prevent them from being used with the argument for the entire expression). However, I encounter an error about a missing argument (value
) when referencing it inconflicts_with
.
Code Snippet:
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
pub struct Command {
#[clap(subcommand)]
pub argument : Arguments,
///...
}
#[derive(Subcommand)]
pub enum Arguments {
Playground,
/// ...
#[clap(about = "Handle quadratic equations")]
Quadratic {
#[clap(subcommand)]
subcommand: QuadraticsCommands,
#[command(flatten)]
input : QuadraticInput
},
}
#[derive(Subcommand)]
pub enum QuadraticsCommands {
Filler
}
#[derive(Args,Debug,Clone)]
#[clap(group = clap::ArgGroup::new(QUAD_GROUP))]
pub struct QuadraticInput {
#[clap(
short='v',
long="value",
help = "The mathematical expression or equation to evaluate (required).",
group = QUAD_GROUP,
conflicts_with_all = ["a","b","c"]
)]
equation_or_expresion : String,
/// Provide the coefficient 'a' of the quadratic equation.
#[clap(
short,
group = QUAD_GROUP,
conflicts_with = "value",
help = "Provide the coefficient 'a' of the quadratic equation."
)]
a: String,
/// Provide the coefficient 'b' of the quadratic equation.
#[clap(
short,
group = QUAD_GROUP,
conflicts_with = "value",
help = "Provide the coefficient 'b' of the quadratic equation."
)]
b: String,
/// Provide the coefficient 'c' of the quadratic equation.
#[clap(
short,
group = QUAD_GROUP,
conflicts_with = "value",
help = "Provide the coefficient 'c' of the quadratic equation."
)]
c: String,
}
Now while running the following command , or any command I get this error
cargo run -- --playground
The error
thread 'main' panicked at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/clap_builder-4.5.8/src/builder/debug_asserts.rs:214:13:
Command quadratic: Argument or group 'value' specified in 'conflicts_with*' for 'a' does not exist
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
How can I achieve the desired behavior using conflicts_with
or other clap
features?
Additional Notes:
- I've tried moving the
value
argument definition before the others, but it didn't work. - I am using this approach due to Support for using ArgGroup as Enum with derive · Issue #2621 · clap-rs/clap · GitHub being unavailiable