0

I'm building a CLI that will be used like this:

$ my_cli command aa aa -- bb bb

Arguments aa aa and bb bb will be collected into separated Vec<String>s. Let's call them vec_a and vec_b. I need both vectors to be the same length. This is what I tried in order to verify that the user gives the same number of values for both arguments:

use clap::{Parser, Subcommand};

// --snip--    

#[derive(Parser)]
#[clap(author, version, about)]
pub struct Cli {
    /// Operation to perform
    #[clap(subcommand)]
    pub command: Subcommands,
}

#[derive(Subcommand)]
pub enum Subcommands {
    // --snip--
    /// does something with vec_a and vec_b. Both must have the same length.
    Rebuild {
        /// Reads vec_a
        #[clap(value_parser, required(true))]
        vec_a: Vec<String>,
        /// Reads vec_b
        #[clap(
            value_parser,
            required(true),
            number_of_values=vec_a.len())]
        vec_b: Vec<String>,
    },
}
// --snip--

I get this error:

~/my_cli$ cargo run -- rebuild aa aa -- bb bb

error[E0425]: cannot find value `vec_a` in this scope
   |
   |             number_of_values=vec_a.len())]
   |                              ^^^^^ not found in this scope

So, how do I check that both arguments have the same length?

Maybe this could be expanded to a more general question: How do I read an argument from the derive properties of another argument?

derch
  • 27
  • 5
  • 1
    I don't think there's a way to do this with clap, but you can always assert that condition yourself after clap has parsed the arguments. – PitaJ Aug 04 '22 at 18:41
  • If the elements from one array are meant to correspond to the other array, you might want to consider a mapping syntax like `aa=bb cc=dd ee=ff` instead. – PitaJ Aug 04 '22 at 18:42

0 Answers0