Search code examples
rusttuples

How to assign 2 args from Commands in clap to 2 vars?


I was trying to get 2 args from Commands in clap. And I a bit stack with it. Here is my code:

use clap::{Parser, Subcommand};

#[derive(Parser, Subcommand)]
enum Commands {
    Remove {
        name: Option<String>,
        path: Option<String>,
    },
}

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

    // I assume here is my issue, however I don't understand how to get it?!
    let x, y = match &args.command {
        Command::Remove { name, path } => name, path,
    };
}

My main issue, I don't know how to match 2 args from Command and assign them at the same time to 2 vars. It returns to the basic Rust knowledge.

It works fine for one argument:

#[derive(Subcommand)]
enum Commands {
    Remove{
        #[arg(short, long)]
        name: Option<String>,
    },
}
...
let x = match &args.command {
    Command::Remove { name } => name,
}

Solution

  • You can use a tuple:

    let (x, y) = match &args.command {
        Command::Remove { name, path } => (name, path),
    };
    

    However, in this case, since the pattern is irrefutable, you can avoid the match at all:

    let Command::Remove { name, path } = &args.command;