Standard Library — The env Module


Contents


The env Standard Library Module

The env module provides access to the process environment — command-line arguments and environment variables. It is a standard library module, not part of the prelude — programs that need environment access must import it explicitly:

use @std.env

Individual functions can be imported selectively:

use @std.env.[args, vars, exit]

args

pub fn args() -> Iterator[str]

Return an iterator over the command-line arguments of the current process. Each element is a string.

The first element is traditionally the path of the executable, but it can be set to arbitrary text and might not even exist. This means the first element should not be relied upon for security purposes.

The iterator yields arguments in order. Each call to args() returns a fresh iterator starting from the first argument.

use @std.env

for arg in env.args()
    println("{arg}")
end

vars

pub fn vars() -> Iterator[Tuple[str, str]]

Return an iterator over a snapshot of the environment variables of the current process. Each element is a Tuple[str, str] where the first element is the variable name and the second is its value.

The snapshot is taken when vars() is called. The iterator is not affected by any environment changes that occur after the snapshot.

The order of variables is platform-dependent and should not be relied upon.

use @std.env

for (name, value) in env.vars()
    println("{name}={value}")
end

exit

pub fn exit(code: int) -> never

Terminate the process immediately with the given exit code. Exit code 0 conventionally indicates success; any non-zero value indicates failure.

Because exit returns never, it can appear in any expression context — the type checker treats it as satisfying any type, just like panic.

use @std.env

fn main()
    match compile(inputPath)
        Ok(_) then env.exit(0)
        Err(msg) then
            println("error: {msg}")
            env.exit(1)
        end
    end
end

exit terminates the process unconditionally. It does not unwind the call stack, run finalizers, or flush buffered output beyond what the underlying runtime provides. Programs that need to ensure output is flushed should call print / println before calling exit.

Examples

Skipping the executable path:

use @std.env

args = env.args().skip(1).toList()
for arg in args
    println("argument: {arg}")
end

Finding a specific environment variable:

use @std.env

home = env.vars()
    .filter(fn(pair) pair.0 == "HOME" end)
    .map(fn(pair) pair.1 end)
    .next()

match home
    Some(path) then println("home directory: {path}")
    None then println("HOME not set")
end

Counting arguments:

use @std.env

count = env.args().count()
println("received {count} arguments")
Link copied to clipboard!