DEV Community

Cover image for Zig vs Go: init and run
Paolo Carraro
Paolo Carraro

Posted on

Zig vs Go: init and run

This is the first post about Zig. As a guide for its exploration, I use my knowledge of Go and consequently I will make a comparison between these two languages wherever possible.

Project Setup

In Go we use
go mod init module-name

while in Zig it's just
zig init

In Zig, "module paths" are not specified as in Go because there is no exact correspondence between package import and its URL: this approach seems more flexible but I must also say less standardized.
Zig also proposes a minimal project scaffold to be able to build or run, or even launch unit tests. Unlike Go which only creates go.mod, this seems like a point in favor of Zig.

Main function

// Go
package main

import (
"fmt"
)

func main() {
    fmt.Println("Hell world")
}
Enter fullscreen mode Exit fullscreen mode
// Zig
const std = @import("std");

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

Enter fullscreen mode Exit fullscreen mode

In both languages, main is the reserved function as the entry point for the application. Both don't accept input parameters and arguments passed must be handled with standard library functions. As for the return, Zig is consistent as it treats main like all other functions (error or value, in this case void) while in Go the success return is implicit and the error must be handled inside the function typically with an os.Exit(1) or a panic("error!").

Build and Run

To run our application we have a very similar command between the two languages. In Go we do
go run main.go
while in Zig
zig run src/main.zig

The same goes for a simple build
go build main.go
zig build src/main.zig
Note the creation of a zig-out/bin folder where we will find the generated binary. This folder is a convention but taking a look at build.zig it becomes very clear how the definition of build, run and test is not provided by the tools but is manageable via code using Zig itself as the language!

Top comments (0)