Arguments
Let’s take a look at how to write command-line programs in Zig. We’ll start with using command-line arguments.
This program simply prints its arguments:
const std = @import("std");
const print = std.debug.print;
// To get just the arguments, we can use
// std.process.Init.Minimal.
pub fn main(minimal: std.process.Init.Minimal) void {
var iterator = minimal.args.iterate();
_ = iterator.skip(); // skip the program name
while (iterator.next()) |arg|
print("{s}\n", .{arg});
}Let’s build the program and run it with three arguments.
$ zig build-exe arguments.zig
$ ./arguments foo bar baz
foo
bar
baz
With zig run we need to put -- before the
arguments.
$ zig run arguments.zig -- foo bar baz
foo
bar
baz
Making it portable
Args.iterate is the most efficient way to get arguments, but it doesn’t work on every platform.
The portable way uses Args.iterateAllocator.
const std = @import("std");
const print = std.debug.print;
// We need an allocator now, so we’ll use
// std.process.Init.
pub fn main(init: std.process.Init) !void {
var iterator =
try init.minimal.args.iterateAllocator(
init.gpa,
);
defer iterator.deinit();
_ = iterator.skip(); // skip the program name
while (iterator.next()) |arg|
print("{s}\n", .{arg});
}$ zig run arguments-2.zig -- foo bar baz
foo
bar
baz
Next example: Environment Variables.