Common Standard Macros
env!
The env! macro inspects an environment variable at compile time and expands to its value as a &'static str literal, failing compilation if the environment variable is not set when rustc runs.
Syntax
env!("VAR_NAME")
env!("VAR_NAME", "custom compile-time error message if VAR_NAME is unset")
Important distinction:
env!("NAME")reads the environment of the build machine at compile time and bakes the resulting string into the binary as a&'static str.std::env::var("NAME")reads the environment of the user's machine at runtime and returnsResult<String, VarError>.
Reading Cargo Metadata Variables at Compile Time
Whenever Cargo compiles a crate, it automatically sets environment variables containing the package metadata from Cargo.toml, which can be embedded into --version banners and user-agent strings with zero runtime cost:
| Cargo Environment Variable | Example Value | Meaning |
|---|---|---|
CARGO_PKG_NAME |
"my_app" |
Package name from Cargo.toml |
CARGO_PKG_VERSION |
"1.4.2" |
Full semantic version (MAJOR.MINOR.PATCH) |
CARGO_PKG_VERSION_MAJOR |
"1" |
Major version component |
CARGO_PKG_DESCRIPTION |
"Fast CLI" |
Package description from Cargo.toml |
OUT_DIR |
"/.../build/out" |
Output directory when a build.rs script is present |
// `PATH` is always defined in the build environment:
const BUILD_PATH_DEFINED: bool = !env!("PATH").is_empty();
fn main() {
println!("PATH was non-empty at compile time: {BUILD_PATH_DEFINED}");
}
PATH was non-empty at compile time: true
Compile-Time Error When Variable Is Missing
If the requested environment variable is not set during compilation, env! halts compilation immediately with your custom error message (or the default message):
// ❌ does not compile
const API_KEY: &str = env!(
"COMPILE_TIME_API_KEY",
"COMPILE_TIME_API_KEY must be set before building this binary"
);
fn main() {}
error: COMPILE_TIME_API_KEY must be set before building this binary
--> src/main.rs:2:23
|
2 | const API_KEY: &str = env!(
| _______________________^
3 | | "COMPILE_TIME_API_KEY",
4 | | "COMPILE_TIME_API_KEY must be set before building this binary"
5 | | );
| |_^