Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provide Default Value for ArgEnum in Rust Clap CLI

Tags:

rust

clap

In Clap, we can use enum as the input for the cli according to https://docs.rs/clap/latest/clap/trait.ValueEnum.html:

#[derive(clap::Parser)]
struct Args {
   #[clap(value_enum)]
   level: Level,
}

#[derive(clap::ValueEnum, Clone)]
enum Level {
   Debug,
   Info,
   Warning,
   Error,
}

We can provide default like so:

struct Args {
   #[clap(value_enum, default_value="debug")]
   level: Level,
}

This works. However, is there a way to provide default value in a type-safe way?

like image 821
Yuchen Avatar asked Dec 13 '25 12:12

Yuchen


1 Answers

Use default_value_t:

use clap::{Parser, ValueEnum};

#[derive(Parser, Debug)]
struct Args {
    #[clap(value_enum, default_value_t=Level::Debug)]
    level: Level,
}

#[derive(ValueEnum, Clone, Debug)]
enum Level {
    Debug,
    Info,
    Warning,
    Error,
}

fn main() {
    println!("{:?}", Args::parse());
}
Args { level: Debug }
like image 87
Finomnis Avatar answered Dec 16 '25 22:12

Finomnis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!