Hello World in Zig

First thing you’ll need to do when starting out with any new programming language is to set up your environment. Luckily, installing Zig is very straightforward, as it is available in many package managers, on Windows, Linux and Mac. If you however would prefer to build from source, that’s very easy too. In that case I would suggest that you follow my Fixing the Zig Compiler article, which instructs how you modify Zig to let you compile even if you have unused parameters or variables in your code.

However, the most straightforward approach on Ubuntu is to use snap to install:

$ snap install zig --classic --beta

If you don’t use Ubuntu, the zig devs have compiled a list of instructions for other package managers.

Zig is in heavy development, and things change. My current version is as follows:

$ zig version
0.12.0-dev.706+62a0fbdae

I built from source myself, so it might not be the same version as distributed by package managers.

The code

The zig commandline tool does a number of things, one of them being initializing your project structure. Find a cozy directory and run zig init-exe:

$ mkdir helloworld
$ cd helloworld
$ zig init-exe

This will generate a build.zig file, as well as src/main.zig. Let’s ignore what’s in that last file for now, and replace it with our own:

const std = @import("std"); 

pub fn main() void {
    std.debug.print("Hello, World!\n", .{});
}

Before we dissect this, let’s build it and run it:

$ zig build
$ ./zig-out/bin/asdf
Hello, World!

It kind of takes a while to compile for the simplest possible program, yes. Let’s start taking in what’s going on, because there are a number of interesting things already.

On line 1, we are doing const std = @import("std"). The import statement basically returns a file as a struct that you can then use in this file, which is pretty nifty. It would also import a package, as is the case with std.

Line 3 consists of fairly recognizable keywords:

Finally, the somewhat verbose printing statement also takes a value, which has to be present but may be left empty. This also works:

    std.debug.print("Hello, {s}!\n", .{"World"});

Comments