Common Standard Macros
option_env!
The option_env! macro inspects an environment variable at compile time and expands to a const-compatible Option<&'static str>: Some("value") if the variable was set during compilation, or None if it was unset.
Syntax and Comparison with env! and std::env::var
const VALUE: Option<&'static str> = option_env!("VAR_NAME");
| Construct | Evaluated At | Return Type | When Variable Is Unset |
|---|---|---|---|
option_env!("NAME") |
Compile time | Option<&'static str> |
Evaluates to None (compilation succeeds) |
env!("NAME") |
Compile time | &'static str |
Compilation fails with an error |
std::env::var("NAME") |
Runtime | Result<String, VarError> |
Returns Err(VarError::NotPresent) at runtime |
Embedding Optional Build Metadata with a Default Fallback
option_env! is commonly paired with .unwrap_or("default") to embed optional CI/CD build metadata (such as GIT_COMMIT_SHA, BUILD_TIMESTAMP, or BUILD_PROFILE) while allowing local cargo build runs without those variables to compile cleanly:
const GIT_COMMIT: &str = match option_env!("GIT_COMMIT_SHA") {
Some(sha) => sha,
None => "dev-local",
};
fn main() {
let build_number = option_env!("CI_BUILD_NUMBER").unwrap_or("unnumbered");
println!("Commit SHA: {GIT_COMMIT}");
println!("Build number: {build_number}");
}
Commit SHA: dev-local
Build number: unnumbered
(Notice that inside a const declaration, match option_env!("...") { Some(v) => v, None => "default" } resolves to a &'static str completely at compile time!)