How to validate two related arguments with clap

Hi all,

I'm learning Rust and I want to write a small game. I need to pass two arguments to the program, one of them is the number of different colours and the number of players. Colours can be 4, 6 or 8 and players can be from 2 to 8, but the relation in between these two params is the number of colours has to be a multiple of the number of players. I have implemented:

fn main() {
    let args = Config::parse();

    if !args.valid() {
            "The relation in between colours {} and players {} is not right.",
            args.colours, args.players
        // HERE

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Config {
    /// Number of colours, allowed are 4, 6 and 8
    #[arg(short, long, default_value_t = 4)]
    colours: u8,

    /// Number for players, allowed are from 2 to 8 and
    /// the number of colours should be multiple of the
    /// number of players
    #[arg(short, long, default_value_t = 4)]
    players: u8,

impl Config {
    fn valid(&self) -> bool {
        (self.colours % self.players) == 0

Is it possible to call some function on Config to show the same text as if the program was called with -h where I have the comment HERE?

Thanks in advance.

Does Command::print_long_help does what you want? You should be able to access the Command of your type that implements Parser with the CommandFactory::command method. That put together, I think Config::command().print_long_help(); at HERE should do what you want.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.