John Graham
John Graham

Reputation: 499

Clap derive enum with non-unit variants?

I'm trying to do this, but clap doesn't like the fact that the variants are non-unit:

#[derive(Clone, Debug, ValueEnum)]
enum Descriptor {
    Id(u32),
    Word(String),
}

#[derive(Debug, Args)]
pub struct MyArgs {
    desc: Descriptor,
}

What do I have to do to make this sort of thing work, or am I stuck having to accept a string and parse it myself?

(N.B. I know there is a similar question here, but it's not fully answered and the comments don't make sense to me)

Upvotes: 0

Views: 346

Answers (1)

Richard Neumann
Richard Neumann

Reputation: 455

As an alternative you can also use a sub-command:

use clap::{Parser, Subcommand};

#[derive(Debug, Parser)]
pub struct MyArgs {
    #[clap(subcommand)]
    desc: Descriptor,
}

#[derive(Clone, Debug, Subcommand)]
enum Descriptor {
    Id { id: u32 },
    Word { word: String },
}

fn main() {
    match MyArgs::parse().desc {
        Descriptor::Id { id } => println!("ID: {id}"),
        Descriptor::Word { word } => println!("Word: {word}"),
    }
}

Which would result in a slightly different but unambiguous CLI interface:

~/subcommand> cargo run -- id 12                                                                                                                                                                                                                                                                                                                                                                                                                                          2023-12-11T12:26:57
   Compiling subcommand v0.1.0 (/home/neumann/subcommand)
    Finished dev [unoptimized + debuginfo] target(s) in 0.41s
     Running `target/debug/subcommand id 12`
ID: 12
~/subcommand> cargo run -- word foo                                                                                                                                                                                                                                                                                                                                                                                                                                       2023-12-11T12:27:01
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/subcommand word foo`
Word: foo
~/subcommand>    

Upvotes: 1

Related Questions