Load secrets from environment variables using std::env::var to keep sensitive data out of your Rust source code.
Manage secrets in Rust by loading them from environment variables at runtime using the std::env module. This keeps sensitive data out of your source code and binary.
use std::env;
fn main() {
let api_key = env::var("API_KEY").expect("API_KEY must be set");
println!("Using API key: {}", api_key);
}
Set the variable before running your program:
export API_KEY="your-secret-key"
cargo run
Secrets are sensitive values like passwords or API keys that should never be saved directly in your code. Instead, you store them in your computer's environment settings and tell your program to look there when it starts. This is like keeping your house key in a locked box outside rather than hiding it under the doormat where anyone can find it.