本頁尚未翻譯,以下為英文原文。
#3.5. env:: - environment variables / args / directories
The std::env module provides a consistent entry point for accessing the process environment. Command-line arguments, environment variables and standard directory paths are gathered in one place, hiding OS differences.
#3.5.1. API
The functions and types the module exposes, at a glance. Path parameters follow the tier-wide argument conventions (Path is P: AsPath).
// command-line arguments
fn args() -> List<str>; // [0] = program name; the runtime captures argc/argv at startup; non-UTF-8 bytes become U+FFFD
fn args_os() -> List<RawStr>; // non-UTF-8 preserved (rare)
// environment variables
fn var(name: str) throws (VarError) -> str;
fn var_os(name: str) -> RawStr | none;
fn vars() -> Vars; // implements Iterator<Item = (str, str)>; non-UTF-8 bytes become U+FFFD
fn vars_os() -> VarsOs; // implements Iterator<Item = (RawStr, RawStr)>
unsafe fn set_var(name: str, value: str) throws (IoError); // InvalidInput for a bad name or value (3.5.3)
unsafe fn remove_var(name: str) throws (IoError); // an unset name is not an error
// directories
fn current_dir() throws (IoError) -> Path; // InvalidData if the path is not UTF-8
fn set_current_dir(path: Path) throws (IoError);
fn home_dir() -> Path | none;
fn temp_dir() -> Path;
fn config_dir() -> Path | none; // macOS ~/Library/Application Support, otherwise $XDG_CONFIG_HOME / ~/.config
fn cache_dir() -> Path | none; // macOS ~/Library/Caches, otherwise $XDG_CACHE_HOME / ~/.cache
fn data_dir() -> Path | none; // macOS ~/Library/Application Support, otherwise $XDG_DATA_HOME / ~/.local/share
// splitting the PATH environment variable (OS-specific separator)
fn split_paths(paths: str) -> List<Path>; // ":" on unix, ";" on windows; empty pieces dropped; windows drops `"` quoting
fn join_paths<I: IntoIterator<Item = P>, P: AsPath>(paths: I) throws (JoinPathsError) -> str;
// the executable itself
fn current_exe() throws (IoError) -> Path; // InvalidData if the path is not UTF-8
// process ID
// the parent's id: os::unix::process::parent_id (3.10.5)
enum VarError {
NotPresent, // the variable does not exist
NotUnicode, // the value is not UTF-8 (read with var_os)
} // message(); + Display, Debug, Error, PartialEq, Eq, Clone, Copy
RawStr is a string holding the bytes exactly as the OS provided them (possibly not UTF-8). JoinPathsError occurs when one of the paths contains the separator (: / ;) or, on Windows, a "; its message names the character.
struct RawStr { /* OS bytes */ }
impl RawStr {
fn len(self) -> usize; // byte length
fn is_empty(self) -> bool;
fn to_str(self) throws (Utf8Error) -> str; // throws if not UTF-8
fn to_str_lossy(self) -> str; // ill-formed parts as U+FFFD
fn as_bytes(self) -> Slice<u8>; // a view, no copy
}
// RawStr: + Clone, PartialEq, Eq, Hash, Debug
struct JoinPathsError { .. } // private fields (0.5.10)
impl JoinPathsError {
fn path(self) -> str; // the path that cannot be joined
fn message(self) -> str;
}
On Windows the bytes are the OS's UTF-16 as WTF-8; there:
impl RawStr {
fn from_wide(wide: Slice<u16>) -> RawStr;
fn as_wide(self) -> Slice<u16>; // a view of a list made for it
}
args, vars and RawStr::to_str_lossy replace each ill-formed part of the bytes with U+FFFD, one per maximal ill-formed subsequence as str::from_utf8_lossy does (2.15.6); on Windows a lone surrogate is one U+FFFD. args_os, vars_os and var_os keep the bytes.
#3.5.2. Examples
How these APIs work together in a real program. The following example shows the typical flow of command-line arguments, environment variables and PATH search in one go.
use std::{env, fs, process};
// CLI tool
let args = env::args();
if args.len() < 2 {
eprintln("usage: tool <input>");
process::exit(1);
}
let input = args[1];
process(input);
// environment variables
let log_level = (try? env::var("LOG_LEVEL")) ?? "info";
let home = env::home_dir() ?? panic("HOME not set");
let config = home / ".config" / "myapp.toml";
// PATH search
let path_str = try env::var("PATH");
for dir in env::split_paths(path_str) {
let candidate = dir / "myprog";
if fs::exists(candidate) {
log(f"found at {candidate:?}");
}
}
#3.5.3. set_var and remove_var are unsafe
set_var and remove_var change the environment of the whole process. The children it spawns later inherit it; to set one child's environment, use Command::env / env_remove (3.6), which is safe.
unsafe { try env::set_var("RUST_LOG", "debug"); } // first thing in main
let child = try Command::new("tool").env("LEVEL", "2").spawn(); // safe: this child only
Both are unsafe fn. Safety: no other thread may read or write the environment during the call, other than through std::env. Nabi's own var, var_os, vars, vars_os, set_var and remove_var take one internal lock, so Nabi code alone does not race; C code that calls getenv or setenv (in a library reached through FFI, for one) does not take it, and a set_var racing with it is undefined behavior on POSIX platforms. A call is sound in a single-threaded program, and on Windows. The recommended pattern is to call set_var at program start, before spawning threads.
Both throw IoError. InvalidInput: the name is empty or holds = or NUL, or the value holds NUL; this check is the same on every target, Windows included. Any other failure is the OS error. Removing a variable that is not set is not an error. A program that wants a panic instead writes try!.
#3.5.4. impl / target
How each platform implements the same semantics:
| Item | linux/macos/windows | wasi |
|---|---|---|
args | argc/argv / GetCommandLine | wasi:cli |
var / vars | getenv / GetEnvironmentVariable | wasi:cli |
home_dir | $HOME / %USERPROFILE% | wasi (no concept) |
temp_dir | $TMPDIR, else /tmp / the first set of %TMP%, %TEMP%, %USERPROFILE%, %SystemRoot%, else C:\Windows (GetTempPath2W's order, read directly) | wasi |
config_dir | XDG / %APPDATA% | (no) |
current_dir | getcwd / GetCurrentDirectoryW | $PWD if absolute and reachable, else / (WASI has none; nabi run / nabi test pass the host's) |
current_exe | /proc/self/exe / _NSGetExecutablePath / GetModuleFileName | Unsupported (wasm32) |
Standard paths use ~/Library/... on macOS, the XDG Base Directory spec on other Unix systems ($XDG_*_HOME is used only when it is an absolute path; otherwise ~/.config and so on), and environment variables on Windows: %USERPROFILE% for home, %APPDATA% for config and data, %LOCALAPPDATA% for cache. The result is none when the variable it reads ($HOME, or the Windows one) is unset or empty.
Found a mistake? Edit this page on GitHub. Last updated