How to parse enum arguments in Rust

In the Rust CLI I’m developing with using Clap, I take some parameters from the end user, which is specified as a struct.

args.rs

use clap:: {
    Args,
    Parser,
    Subcommand
};

#[derive(Debug, Parser)]
#[clap(author, version, about)]
pub struct CLIArgs {
    #[clap(subcommand)]
    pub action: CLIAction,
}

#[derive(Debug, Subcommand)] 
pub enum CLIAction {
    Run(RunCommand),

    Copy(CopyCommand),
}

#[derive(Debug, Args)]
pub struct RunCommand {
    pub app: String,

    #[clap(long)]
    pub from: String,

    #[clap(long)]
    pub against: String
}

#[derive(Debug, Args)]
#[derive(Default)]
pub struct CopyCommand {
    pub app: String,
}

I use this file in my main.rs as follows.

main.rs

use clap::Parser;

mod args;

use args::CLIArgs;

fn main() {
    let args: CLIArgs = CLIArgs::parse();
    println!("{:?}",args.action);
}

When executing the following run command,

cli run console –from id –against local

The print statement in the main method prints the following, but I’m unable to parse this in order to get specific properties from this. 🙁

Run(RunCommand { app: "console", from: "id", against: "local" })

Ideally I want to do something like,

args.action.app -> returns "console"

Any idea how to properly parse the args.action and get the above done? Thanks in advance.

>Solution :

The easiest way to parse the args is to use a match statement. You can use it to match the enum variant and then destructure the associated struct to get the properties you need.

fn main() {
    let args: CLIArgs = CLIArgs::parse();
    match args.action {
        CLIAction::Run(RunCommand { app, from, against }) => {
            println!("App: {}, From: {}, Against: {}", app, from, against);
        },
        CLIAction::Copy(CopyCommand { app }) => {
            println!("App: {}", app);
        }
    }
}

Leave a Reply