Skip to main content

load_dotenv

Function load_dotenv 

Source
pub fn load_dotenv() -> &'static HashMap<String, String>
Expand description

Load environment variables from a .env file into the process environment.

  1. Walks upward from CARGO_MANIFEST_DIR (if set) or the current working directory to find the nearest .env file.
  2. Parses each KEY=VALUE line (skipping blanks and #-comments).
  3. For every key that is not already present in the process environment, calls std::env::set_var to inject it.
  4. Returns a HashMap of the newly-set key/value pairs (keys that were already set are omitted).

Results are cached via OnceLock — the file is read and environment variables are set at most once. Subsequent calls return a clone of the cached map without re-reading the file or modifying the environment.

§Safety

This function calls std::env::set_var, which is not thread-safe. It must be called during single-threaded startup, before any additional threads are spawned (including the Tokio runtime). Calling it after threads exist is undefined behaviour.

§Example

let new_vars = agy_bridge::load_dotenv();
// OnceLock-cached: safe to call multiple times, only loads .env once.
let _ = new_vars.len();