Function std::env::set_var

1.0.0 · source ·
pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V)
Expand description

Sets the environment variable key to the value value for the currently running process.


Even though this function is currently not marked as unsafe, it needs to be because invoking it can cause undefined behaviour. The function will be marked unsafe in a future version of Rust. This is tracked in rust#27970.

This function is safe to call in a single-threaded program.

In multi-threaded programs, you must ensure that are no other threads concurrently writing or reading(!) from the environment through functions other than the ones in this module. You are responsible for figuring out how to achieve this, but we strongly suggest not using set_var or remove_var in multi-threaded programs at all.

Most C libraries, including libc itself do not advertise which functions read from the environment. Even functions from the Rust standard library do that, e.g. for DNS lookups from std::net::ToSocketAddrs.

Discussion of this unsafety on Unix may be found in:


This function may panic if key is empty, contains an ASCII equals sign '=' or the NUL character '\0', or when value contains the NUL character.


use std::env;

let key = "KEY";
env::set_var(key, "VALUE");
assert_eq!(env::var(key), Ok("VALUE".to_string()));