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
The env! macro lets you grab a value from your computer's environment settings and bake it directly into your program while it is being built. This is useful for things like version numbers or configuration flags that shouldn't change while the program is running. Think of it like stamping a date onto a product at the factory; once it's stamped, you can't change it without making a new product.