How to Manage Secrets in Rust Applications

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