Sub topic 9
Defaults and environment variables
This chapter assumes you can define a CLI with #[derive(Parser)], declare options with #[arg(long)], and read typed fields from the parsed struct. It also assumes you know Option<T> and basic shell use of export.
Why defaults matter
An option that the user leaves out has to get a value from somewhere. clap resolves each argument from these sources, in this order:
- The command line.
- An environment variable, if you declared one with
env. - A default value, if you declared one.
If none of these supplies a value, the field is None for an Option<T>. A required argument produces a parse error instead.
Setting a default
Use default_value_t when the default is a Rust value. clap formats it as text and runs it through the same parser as user input. The type must implement Display. Use default_value when you want to write the default as a string yourself.
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
/// Port to listen on
#[arg(long, default_value_t = 8080)]
port: u16,
/// Address to bind
#[arg(long, default_value = "127.0.0.1")]
host: String,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}Running with no arguments prints Cli { port: 8080, host: "127.0.0.1" }. The generated --help also shows [default: 8080] for you.
Reading from the environment
The env feature must be enabled in Cargo.toml:
[dependencies]
clap = { version = "4", features = ["derive", "env"] }Then name the variable in the attribute:
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
/// API token, read from APP_TOKEN if not given on the command line
#[arg(long, env = "APP_TOKEN", hide_env_values = true)]
token: Option<String>,
/// Port to listen on
#[arg(long, env = "APP_PORT", default_value_t = 8080)]
port: u16,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}With APP_PORT=9000 exported, --port is not needed and port is 9000. Passing --port 7000 still wins. Writing env with no value, as in #[arg(long, env)], makes clap derive the variable name from the field, here PORT. Naming it explicitly is safer because a short generic name can collide with other programs.
hide_env_values = true keeps the secret out of the --help output, which otherwise prints the current value of a set variable.
Common mistakes
- Forgetting the feature. Without
envinfeatures,env = "..."fails to compile. - Default for a secret. Do not give tokens a default. An absent secret should be
Noneso your code can report it. - Invalid environment values. The value from the environment goes through the same
value_parseras the command line.APP_PORT=abcproduces a normal clap parse error, not a silent fallback to the default. - Empty variables. A variable that is set but empty counts as set, so it can override the default with an empty string. Check that your parser rejects empty values if that matters.
Exercise
A struct has #[arg(long, env = "APP_PORT", default_value_t = 8080)] port: u16. The shell has APP_PORT=9000 exported, and the user runs app --port 7000. What is port, and what would it be if the user ran app with APP_PORT=abc exported?
Show answer
With --port 7000, port is 7000, because the command line takes priority over the environment. With APP_PORT=abc and no flag, clap does not fall back to 8080. It reports a parse error because "abc" fails the u16 parser, and the program exits with a non-zero status.