Add the dotenvy crate to your dependencies, create a .env file in your project root, and call dotenvy::dotenv() at the start of your main function to load variables into the environment.
use dotenvy::dotenv;
use std::env;
fn main() -> Result<(), dotenvy::Error> {
dotenv()?;
let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
println!("Connecting to: {}", db_url);
Ok(())
}
Add this to Cargo.toml:
[dependencies]
dotenvy = "0.15"
Create a .env file in the project root:
DATABASE_URL=postgres://user:pass@localhost/mydb