How to Use Compile-Time Environment Variables in Rust (env! macro)

Use the env! macro to embed environment variable values as string literals at compile time in Rust.

Use the env! macro to embed environment variable values as string literals at compile time, which fails if the variable is missing. Set the variable in your shell before running cargo build, then call env! with the variable name in your code.

fn main() {
    let version = env!("CARGO_PKG_VERSION");
    println!("Version: {}", version);
}

Run this with the variable set:

export CARGO_PKG_VERSION="1.0.0"
cargo run