Working with clap and Subcommand

Good Morning,
First of all I'm really newby and, perhaps, I started a personal project bigger of my capability.
Also, apologize for my bad english.

I'm working on a project that implement AWS SDK and I chose clap to rationalize the command line arguments, options and subcommands.

The start code should be simple:

extern crate ini;

use clap::{Parser, Subcommand};

#[derive(Debug, Parser)]
#[clap(name = "zaw", version)]
pub struct AppArguments {
    options: AppOptions,

    subcommand: AppSubCommand

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct AppOptions {
    #[arg(long = "account", short = 'a')]
    accountid: String,

    #[arg(long = "region", short = 'r', default_value_t = ("null").to_string())]
    region: String,

#[derive(Debug, Subcommand, Clone)]
enum AppSubCommand {
    Discovery {
        #[arg(long = "service", short = 's', default_value_t = ("null").to_string())]
        service: String,
    Getmetric {
        #[arg(long = "service", short = 's', default_value_t = ("null").to_string())]
        service: String,

        #[arg(long = "metric", short = 'm', default_value_t = ("null").to_string())]
        metric: String,

fn main() {

    let application_arguments = AppArguments::parse();
    println!("AppArguments.....: {:?}", &application_arguments);
    println!("Options..........: {:?}", &application_arguments.options);
    println!("AccountID........: {:?}", &application_arguments.options.accountid);
    println!("AccountRegion....: {:?}", &application_arguments.options.region);
    println!("SubCommand.......: {:?}", &application_arguments.subcommand);


So far no problem but i'm not able to retrive service in inside Discovery or GetMetric into AppSubCommand enum

with compiler error:

error[E0609]: no field `service` on type `AppSubCommand`
  --> src/
63 |     println!("Service..........: {:?}", &application_arguments.subcommand.service);
   |                                                                           ^^^^^^^ unknown field

Can some help me to understand this problem or pointing me to the specific part in manual to understand where i'm failing?

Thanks in advance.

You can't access fields of enum variants like that, even if they are shared across every variant. You somehow have to extract the value from your variants via pattern matching. If I were you, I'd simply create a service method on AppSubCommand:

impl AppSubCommand {
    fn service(&self) -> &str {
        match self {
            Self::Discovery { service } => service,
            Self::Getmetric { service, .. } => service,

and call it in your main function like:

println!("Service..........: {:?}", &application_arguments.subcommand.service());

Really thank you for fast and clear reply!

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.