pub unsafe fn apply(environment: &LoadedEnvironment) -> Result<(), ApplyError>Expand description
Sets every loaded key to its loaded value in the current process environment.
First runs validate, so an environment it rejects changes nothing. Then
sets each key with std::env::set_var, in sorted order. A loaded key
replaces a variable of the same name. Other variables are kept and nothing
is removed. Values are set as loaded, without expanding references such as
${HOME}. The changes cannot be rolled back.
Prefer passing LoadedEnvironment::values to a child process, or reading
the values directly, unless code you do not control reads the process
environment. See the crate documentation.
§Errors
Returns the ApplyError from validate, before changing anything.
§Safety
No other thread may read or write the process environment while apply
runs. That includes std::env::var and C functions such as getenv and
setenv called by libraries. On some platforms such concurrent access is
undefined behavior. In practice, call apply at the start of main, before
starting threads or an async runtime.
§Examples
With APP_PORT=8080 and APP_HOST=0.0.0.0 in .env:
use adotenv::load::load_cascade;
use adotenv_process::apply;
let loaded = load_cascade(&dir, "")?;
// SAFETY: called at startup, before any other thread exists.
unsafe { apply(&loaded)? };
assert_eq!(std::env::var("APP_PORT")?, "8080");
assert_eq!(std::env::var("APP_HOST")?, "0.0.0.0");