Zig standard library historically had a major footgun: std.os.environ was meant to be equivalent to environ in C, which forced it to be populated it in a library linked to libc. But C is designed to avoid calling environment-modifying functions like setenv in a threaded context, because environ often is directly accessed without lock-ing. That’s why now environment variables are available only in the application’s main function, so functions that need access env vars can accept parameters for the needed values, or accept a *const process.Environ.Map parameter. This is where the “Juicy main” comes into play: an instance of this environment variable map can be obtained via the init parameter.
Inspecting how the new Juicy main works, it’s worth noting that you can access Minimal, with Init as its superset, and used as the first parameter of main as well.
pub fn main(init: std.process.Init) !void {
// Obtain the process-lifetime arena allocator provided by Init.
// This allocator is intended for allocations that live for the
// entire duration of the program.
const arena: std.mem.Allocator = init.arena.allocator();
// Access command-line arguments through the environment map.
// `keys()` returns an iterator over the argument keys
// (arguments are stored as entries in the environment map).
const args_em = init.environ_map.keys();
// Iterate through arguments obtained from the environment map
// and log each one.
for (args_em) |arg| {
std.log.info("arg_em: {s}", .{arg});
}
// Access command-line arguments via the Minimal interface.
// `toSlice` materializes the arguments into a slice using
// the provided allocator.
const args_min = try init.minimal.args.toSlice(arena);
// Iterate through the slice of arguments obtained from Minimal
// and log each one.
for (args_min) |arg| {
std.log.info("arg_min: {s}", .{arg});
}
}
*Environ.Map
Output:
$ zig build run -- param_1
info: arg_em: SHELL
info: arg_em: SESSION_MANAGER
...
info: arg_em: COLORTERM
info: arg_em: MATRIX_ROOM_ID
info: arg_em: XDG_CONFIG_DIRS
info: arg_em: NVM_INC
info: arg_em: XDG_MENU_PREFIX
info: arg_em: GTK_IM_MODULE
...
info: arg_em: XMODIFIERS
info: arg_em: DESKTOP_SESSION
info: arg_em: MATRIX_HOMESERVER
info: arg_em: EDITOR
info: arg_em: GOBIN
info: arg_em: GTK_MODULES
info: arg_em: XDG_SEAT
...
info: arg_em: VTE_VERSION
info: arg_em: DENO_INSTALL
info: arg_em: QTWEBENGINE_DICTIONARIES_PATH
info: arg_em: CLUTTER_IM_MODULE
info: arg_em: NVM_DIR
info: arg_em: LESSCLOSE
info: arg_em: XDG_SESSION_CLASS
info: arg_em: TERM
info: arg_em: GTK_OVERLAY_SCROLLING
info: arg_em: LESSOPEN
info: arg_em: USER
info: arg_em: DISPLAY
info: arg_em: SHLVL
...
info: arg_em: OLDPWD
info: arg_em: _
info: arg_em: CLICOLOR_FORCE
info: arg_min: /home/foo/bar/baz/zig-out/bin/recap_args
info: arg_min: param_1
Output
AdP