Zig for Go Developers
Go and Zig have more in common than you might think. Both value simple, readable code over clever features. Both return errors as values instead of throwing exceptions. Both have defer, a built-in formatter, and a single command that builds, tests and cross-compiles. The big differences are underneath: Go has a garbage collector and a runtime that schedules goroutines for you, and Zig has neither. This page shows what that means in practice, with Go and Zig side by side. The Go examples were run with Go 1.24 and the Zig ones with Zig 0.17.1.
The quick map
Section titled “The quick map”| In Go | In Zig | Lesson |
|---|---|---|
| Garbage collector | Allocators you pass in, defer gpa.free(...) |
Zig Allocators |
make([]T, n), append |
gpa.alloc(T, n), std.ArrayList(T) |
Zig ArrayList |
map[K]V |
std.AutoHashMapUnmanaged(K, V) / std.StringHashMapUnmanaged(V) |
Zig HashMap |
error, if err != nil |
Error unions, try, catch |
Zig Errors |
go f(), channels |
io.async(f, ...), threads, std.Io.Queue |
Zig Async & Futures |
nil |
null with optional types ?T |
Zig Optionals |
| Zero values | Explicit values, or undefined |
Zig Variables |
| Interfaces (implicit) | anytype, tagged unions, vtables |
Zig Interfaces |
String() method |
format method, printed with {f} |
Zig Format Strings |
| Capitalized name = exported | pub |
Zig Modules |
go build, go test, go.mod |
zig build, zig build test, build.zig.zon |
Zig Build System |
GOOS=windows go build |
zig build -Dtarget=x86_64-windows |
Zig Cross-Compiling |
No garbage collector
Section titled “No garbage collector”In Go you create things and forget about them; the GC frees them once nothing points at them. Zig has no GC, so memory you allocate stays allocated until you free it. To make that manageable, Zig has one firm rule: a function that needs heap memory takes an allocator as a parameter. You can see from a function’s signature whether it allocates, and the caller decides where the memory comes from. The Memory section of the language reference explains the thinking behind it.
const std = @import("std");
fn squares(gpa: std.mem.Allocator, n: usize) ![]u64 { const out = try gpa.alloc(u64, n); for (out, 0..) |*square, i| square.* = i * i; return out;}
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const nums = try squares(gpa, 5); defer gpa.free(nums); std.debug.print("{any}\n", .{nums});}Output:
{ 0, 1, 4, 9, 16 }In Go this would be s := make([]uint64, n) and you’d never think about it again. In Zig:
gpa.alloc(u64, n)asks the allocator for room fornnumbers. It can fail witherror.OutOfMemory, so it needstry, andsquaresreturns an error union (![]u64).squareshands the memory to its caller. The caller frees it, anddefer gpa.free(nums)makes sure that happens whenmainends, like a Godeferwould.init.gpareports leaks in debug builds. Delete thedeferline and the program prints where the leaked memory was allocated.
Arenas: Go’s “just forget it”, on purpose
Section titled “Arenas: Go’s “just forget it”, on purpose”A lot of Go code is “handle a request, make a pile of small objects, return”. Zig has a tool that fits that shape well: an arena. You allocate as much as you like from it and free everything at once at the end:
const std = @import("std");
fn handleRequest(gpa: std.mem.Allocator, user: []const u8) !void { var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const a = arena.allocator();
const greeting = try a.print("Hello, {s}!", .{user}); const shout = try std.ascii.allocUpperString(a, greeting); std.debug.print("{s} / {s}\n", .{ greeting, shout });}
pub fn main(init: std.process.Init) !void { try handleRequest(init.gpa, "ada"); try handleRequest(init.gpa, "linus");}Output:
Hello, ada! / HELLO, ADA!Hello, linus! / HELLO, LINUS!Neither string is freed one by one: arena.deinit() frees the lot when the request is done. It feels a lot like having a GC for the length of one request, with no collector running in the background. Zig Arena Allocator goes further.
Error values in both
Section titled “Error values in both”This part will feel like home. Go returns (value, error); Zig returns an error union, a value or an error in one. Here’s a sentinel error passed up through a second function:
package main
import ( "errors" "fmt")
var ErrNotFound = errors.New("user not found")
func findUser(id int) (string, error) { if id == 1 { return "Ada", nil } return "", ErrNotFound}
func greet(id int) (string, error) { name, err := findUser(id) if err != nil { return "", fmt.Errorf("greet %d: %w", id, err) } return "Hello, " + name, nil}
func main() { for _, id := range []int{1, 2} { msg, err := greet(id) if errors.Is(err, ErrNotFound) { fmt.Println("error:", err) continue } fmt.Println(msg) }}Output:
Hello, Adaerror: greet 2: user not foundconst std = @import("std");
fn findUser(id: u32) error{NotFound}![]const u8 { if (id == 1) return "Ada"; return error.NotFound;}
fn greet(buf: []u8, id: u32) ![]u8 { const name = try findUser(id); return std.mem.print(buf, "Hello, {s}", .{name});}
pub fn main() void { var buf: [64]u8 = undefined; for ([_]u32{ 1, 2 }) |id| { const msg = greet(&buf, id) catch |err| switch (err) { error.NotFound => { std.debug.print("error: user {d} not found\n", .{id}); continue; }, else => |e| { std.debug.print("error: {t}\n", .{e}); continue; }, }; std.debug.print("{s}\n", .{msg}); }}Output:
Hello, Adaerror: user 2 not foundHow they line up:
try findUser(id)is Zig’sif err != nil { return err }in one word.error.NotFoundplays the part ofErrNotFound, andswitchon the error replaceserrors.Is. You don’t declare error values up front; usingerror.NotFoundis enough.greetreturns![]u8, and Zig works out its error set itself:NotFoundfromfindUserplusNoSpaceLeftfrom formatting into a buffer. That’s why theswitchneeds anelse: the compiler knows every error that can come out and makes you deal with all of them.- You can’t ignore an error. In Go,
msg, _ := greet(2)compiles. In Zig, using the result ofgreetwithouttryorcatchis a compile error.
The one thing Zig errors can’t do is carry a message or wrap another error like %w: they’re just names. When you need details, you pass a small struct in and fill it before returning the error. In return, debug builds print an error return trace that shows every try the error went through, so you rarely need wrapping just to find where it came from. See Zig Error Return Traces.
No goroutines
Section titled “No goroutines”Go’s runtime schedules goroutines onto threads for you, and channels connect them. Zig has no runtime like that. There are two tools instead:
std.Thread.spawn: a real operating system thread, for CPU work in parallel (Zig Threads).io.async: start a function that may run at the same time as other work, through theiovalue your program gets frommain(Zig Async & Futures).
Here’s “fetch two things at once” in Go:
package main
import ( "fmt" "time")
func fetch(name string, ms int) string { time.Sleep(time.Duration(ms) * time.Millisecond) return name}
func main() { start := time.Now() weather := make(chan string) news := make(chan string) go func() { weather <- fetch("weather", 600) }() go func() { news <- fetch("news", 400) }() fmt.Println("got", <-weather, "and", <-news) fmt.Println("took about", time.Since(start).Round(100*time.Millisecond).Milliseconds(), "ms")}Output:
got weather and newstook about 600 msAnd in Zig:
const std = @import("std");const Io = std.Io;
fn fetch(io: Io, name: []const u8, ms: i64) ![]const u8 { try io.sleep(.fromMilliseconds(ms), .awake); return name;}
pub fn main(init: std.process.Init) !void { const io = init.io; const start = Io.Timestamp.now(io, .awake);
var weather = io.async(fetch, .{ io, "weather", 600 }); defer _ = weather.cancel(io) catch {}; var news = io.async(fetch, .{ io, "news", 400 }); defer _ = news.cancel(io) catch {};
std.debug.print("got {s} and {s}\n", .{ try weather.await(io), try news.await(io) }); const ms = start.untilNow(io, .awake).toMilliseconds(); std.debug.print("took about {d} ms\n", .{@divTrunc(ms, 100) * 100});}Output:
got weather and newstook about 600 msBoth finish in about 600 ms, not 1000. The Zig version reads differently:
io.async(fetch, .{ ... })returns a future instead of needing a channel.awaitgives you the result, errors included.fetchis an ordinary function. It takesioas a parameter, the way it would take an allocator, so the same function can be called directly or started withio.async. Nothing is markedasync.- Cleanup is yours.
defer ... cancel(io)makes sure a task is stopped and its resources freed even ifmainreturns early. A Go goroutine that nobody waits for just keeps running; a Zig future that nobody awaits or cancels is a leak. - “May run at the same time” isn’t “will”.
io.asyncis allowed to run the function right away if there’s no way to run it in parallel. When you truly need two things running together (say, a producer and a consumer), you useio.concurrent, which fails with an error instead of quietly running one after the other. Zig Async & Futures explains the difference.
This part of Zig is new (it arrived in Zig 0.16) and still changing, and there’s nothing as complete as Go’s scheduler and net/http in the standard library yet. If your program is mostly “many network connections at once”, Go is the easier tool today.
defer runs at the end of the block
Section titled “defer runs at the end of the block”Both languages have defer, but they don’t run it at the same time. Go runs deferred calls when the function returns. Zig runs them when the block ends:
package main
import "fmt"
func main() { for i := 1; i <= 3; i++ { defer fmt.Println("deferred", i) fmt.Println("loop", i) } fmt.Println("end of main")}Output:
loop 1loop 2loop 3end of maindeferred 3deferred 2deferred 1const std = @import("std");
pub fn main() void { for (1..4) |i| { defer std.debug.print("deferred {d}\n", .{i}); std.debug.print("loop {d}\n", .{i}); } std.debug.print("end of main\n", .{});}Output:
loop 1deferred 1loop 2deferred 2loop 3deferred 3end of mainIn Zig, a defer inside a loop body runs at the end of each pass. That’s usually what you want (open a file, process it, close it, next file), and it’s the opposite of the Go gotcha where deferred closes pile up until the function returns. Zig also has errdefer, which runs only when the function returns an error: see Zig Errdefer.
Interfaces and String()
Section titled “Interfaces and String()”Go interfaces are satisfied implicitly: any type with a String() string method is a fmt.Stringer. Zig works in a similar spirit. There’s no interface keyword, but code that takes anytype works with any type that has the methods it uses, checked when compiling. The formatting functions are a good example. Give a struct a pub fn format and {f} calls it:
package main
import "fmt"
type Point struct { X, Y int}
func (p Point) String() string { return fmt.Sprintf("(%d, %d)", p.X, p.Y)}
func main() { p := Point{X: 3, Y: 4} fmt.Println("point:", p)}const std = @import("std");
const Point = struct { x: i32, y: i32,
pub fn format(self: Point, writer: *std.Io.Writer) std.Io.Writer.Error!void { try writer.print("({d}, {d})", .{ self.x, self.y }); }};
pub fn main() void { const p: Point = .{ .x = 3, .y = 4 }; std.debug.print("point: {f}\n", .{p});}Output:
point: (3, 4)Both print point: (3, 4). One difference: Zig’s format writes into a writer instead of returning a new string, so it doesn’t allocate. For “a list of different shapes” at runtime, the kind of thing you’d use an interface value for in Go, Zig uses a tagged union or a struct of function pointers. Zig Interfaces covers both.
Tools: go vs zig
Section titled “Tools: go vs zig”| Go | Zig |
|---|---|
go mod init |
zig init |
go build |
zig build (or zig build-exe main.zig for one file) |
go run . |
zig build run (or zig run main.zig) |
go test ./... |
zig build test |
gofmt -w . |
zig fmt . |
go get example.com/pkg |
zig fetch --save <url> |
GOOS=linux GOARCH=arm64 go build |
zig build -Dtarget=aarch64-linux |
Like Go, Zig has testing built in (test blocks next to your code, see Zig Testing) and cross-compiles without extra toolchains. Unlike Go, the build script is a Zig program (build.zig), and there’s no module proxy or central package index: dependencies are URLs with a hash, listed in build.zig.zon. See Zig Packages.
Things that will trip you up
Section titled “Things that will trip you up”- No zero values.
var count: i32;is a syntax error in Zig. Give every variable a value, or writeundefinedon purpose when you’ll fill it in before reading it. - Unused things are errors, like in Go, but Zig goes further: unused function parameters and a
varthat’s never changed are errors too. - No
appendthat quietly reallocates. A Zig slice has a fixed length. For a growing list, usestd.ArrayList, which takes the allocator on every call that might grow it. - Strings are byte slices (
[]const u8), there’s nostringtype, and joining them needs memory:++only works for strings known at compile time. - Integer types don’t mix. You can’t add an
i32to ani64field without a cast, and overflow is a crash in debug builds, not a silent wrap. - Zig isn’t 1.0. Go’s compatibility promise has no Zig equivalent yet. New releases break code, so check which version an example was written for.
Practice
Section titled “Practice”1. A Go function, ported
Section titled “1. A Go function, ported”Port this Go function to Zig. It returns the index of the first negative number, or an error if there is none.
var ErrNoNegative = errors.New("no negative number")
func firstNegative(nums []int) (int, error) { for i, n := range nums { if n < 0 { return i, nil } } return 0, ErrNoNegative}Hint: the return type is !usize, and for (nums, 0..) |n, i| gives you the item and its index.
Show solution
const std = @import("std");
fn firstNegative(nums: []const i32) !usize { for (nums, 0..) |n, i| { if (n < 0) return i; } return error.NoNegative;}
pub fn main() void { if (firstNegative(&.{ 4, 7, -2, 9 })) |i| { std.debug.print("first negative at {d}\n", .{i}); } else |err| { std.debug.print("error: {t}\n", .{err}); } _ = firstNegative(&.{ 1, 2 }) catch |err| std.debug.print("error: {t}\n", .{err});}Output:
first negative at 2error: NoNegativeThere’s no “zero value plus error” to return: a Zig function returns either the index or the error, never both. if (...) |i| ... else |err| is the Zig way to look at both outcomes.
2. Clean up per loop pass
Section titled “2. Clean up per loop pass”Use an arena per loop pass: for each name in "ada", "grace", make an upper-case copy with std.ascii.allocUpperString and print it. Free everything at the end of each pass with one defer.
Hint: create the arena inside the loop body; defer arena.deinit(); then runs at the end of every pass.
Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void { for ([_][]const u8{ "ada", "grace" }) |name| { var arena: std.heap.ArenaAllocator = .init(init.gpa); defer arena.deinit(); const upper = try std.ascii.allocUpperString(arena.allocator(), name); std.debug.print("{s}\n", .{upper}); }}Output:
ADAGRACEBecause Zig’s defer runs at the end of the block, each pass frees its own memory before the next one starts. In Go, the same defer would wait for the whole function.
- Zig has no GC: functions take an allocator, and you free with
defer. Arenas give you “free it all at the end” on purpose. - Errors are values in both, but Zig’s
tryreplacesif err != nil, the compiler makes you handle every error, and errors carry no message. - No goroutines: use
io.asyncfor “at the same time” andstd.Threadfor parallel CPU work, and clean up every future. - Zig’s
deferruns at the end of the block, not the function. anytypeand aformatmethod play the role of implicit interfaces andString().- No zero values, no
append, stricter integers, and no 1.0 promise yet.
Next up: Zig for Python Developers, what’s different coming from a dynamic language.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig in-depth overview: Zig’s design, including manual memory management and no hidden allocations.
- Zig language reference: Memory: why Zig makes you pass allocators, and how to pick one.
- Zig 0.16.0 release notes: where
std.Io,io.asyncand futures were introduced. - Effective Go: the Go side, if you want to compare idioms.