Call Zig from Go without cgo.
zigo builds a Zig library into a memory image, generates Go functions for its exported functions, and loads the image when your program first calls it. Your program stays a single binary built with CGO_ENABLED=0, which is static on Linux, and building it needs only Go: the generated files are committed. They have no dependencies, not even on zigo, so your library is portable too: any program can use it.
It also works with C, which Zig compiles, including C that needs libc: sqlite is an SQLite package for Go, with a database/sql driver, that needs no cgo. In its benchmarks, it is usually faster than the other SQLite drivers tested, including those that use cgo.
It works with small Zig files and with existing Zig projects: examples/ghostty runs Ghostty's terminal emulator library, libghostty-vt, which go-libghostty calls through cgo.
// walk.zig
const zigo = @import("zigo");
export fn count_byte(s: zigo.String, byte: u8) usize {
var n: usize = 0;
for (s.slice()) |c| n += @intFromBool(c == byte);
return n;
}//go:generate go run github.com/sprisa/zigo walk.zig
n := CountByte("banana", 'a') // 3Functions that return or take many rows can pass them in batches, so that each row costs a few nanoseconds rather than a call:
comptime {
zigo.stream("users", Users, .{}); // Users has a next function.
}for user, err := range lib.Users(users) {Status: experimental. Linux and macOS, on amd64 and arm64. On other platforms the generated code compiles, and calls panic with an error that is errors.ErrUnsupported.
- Go 1.26 or newer.
- Zig 0.17 to generate. Building the Go package afterwards needs only Go.
Put the Zig source in a Go package directory, then add a go:generate line to one of the package's Go files:
//go:generate go run github.com/sprisa/zigo walk.ziggo generate writes these files. Commit them all:
| File | Contents |
|---|---|
zigo.go |
A Go function for each exported function, and a list of those zigo skipped |
__zigo__/zigo_<os>_<arch>.zigo |
The image: the compiled library's code and data, as they are laid out in memory, and tables of its pointers, functions and source lines |
__zigo__/zigo_<os>_<arch>.go |
The image's layout and the exported functions' offsets |
__zigo__/zigo_other.go |
Stubs for platforms the library does not support |
__zigo__/zig/ |
The library's own copy of zigo's runtime, which loads the image and calls into it |
zigo.go is the package's API, which your own code in the package can add to. __zigo__ and __zigo__/zig are packages of their own. The go tool skips directories starting with _ in patterns like ./..., so it stays out of the way.
The images are committed so that building your package needs only Go, as go:embed puts them into the binary. Without them, every build would need Zig, the way cgo needs a C compiler. There is one for each platform, and a program only includes its own. Their size is the library's: up to 30 KB each for the basic example, 1.7 MB for SQLite, and 2.5 MB for libghostty-vt. They are reproducible: the same Zig version generates the same files on any machine. That includes those for macOS, which you can generate on Linux.
Each package holds one zigo library. zigoLib.Available() reports whether the current platform supports it.
Zig does not allow relative imports from outside the directory of the library's file. To share code between libraries, make it a module in a build.zig, and run zigo in that directory:
// build.zig
const shared = b.createModule(.{ .root_source_file = b.path("shared/shared.zig") });
const lib = b.createModule(.{
.root_source_file = b.path("lib/lib.zig"),
.target = b.standardTargetOptions(.{}),
});
lib.addImport("shared", shared);
b.installArtifact(b.addLibrary(.{ .name = "lib", .root_module = lib }));//go:generate go run github.com/sprisa/zigo lib/lib.zigzigo finds the first library or program in the build's steps whose root file is the given one, and adds the modules it imports, including indirect ones and those from packages. If there is none, or the current directory has no build.zig or does not contain the file, the file can only import zigo and Zig's own modules. zigo does not look for a build.zig in parent directories. examples/modules shows this.
- zigo only uses the modules, not other settings, such as C files, include paths, libc or optimization. It compiles modules with its own settings.
- It reads
build.zig's default configuration, once for all platforms. Ifbuild.zigchooses modules for a specific target, they may be wrong for the platforms zigo builds for. - Modules must be source files. zigo stops with an error if the build generates one, as
addOptionsdoes. @import("zigo")in the library's file is always zigo's own module, even ifbuild.zighas an import with that name. Other modules can only importzigoifbuild.ziggives them one, which is not zigo's.- As with
zig build, ifbuild.zig.zonhas packages to download, Zig puts them inzig-pkg.
Given a directory, zigo builds it as a project instead, as below. -add's file cannot import these modules.
Given a directory instead of a .zig file, zigo runs the project's build.zig once per platform with -Dtarget, -Dcpu and -Doptimize, and links the static library it installs:
//go:generate go run github.com/sprisa/zigo -export ghostty_ -trim ghostty_ .The build must use b.standardTargetOptions and b.standardOptimizeOption, build position-independent code, and install one static library under lib/. A library built this way keeps its own panic handler, so a Zig panic crashes the program with Go's crash report rather than becoming a Go panic.
This is also how to use C: list its source files in build.zig, as sqlite/lib does. C libraries need these settings on their module:
.link_libc = true, for libc's headers, if they use them..sanitize_c = .off. Otherwise, Zig adds checks for undefined behavior to C in Debug builds, which need functions that zigo does not link, such as__ubsan_handle_mul_overflow..stack_protector = false. On amd64, stack protectors read the thread pointer, which belongs to Go's runtime. zigo reports an error if they are on.- No optimization in Debug builds, since zigo reads function signatures from one. That is Zig's default, so leave out flags like
-O2.
| Flag | Default | Meaning |
|---|---|---|
-o |
. |
Output Go package directory |
-pkg |
$GOPACKAGE |
Go package name |
-importpath |
from go.mod |
The output package's import path |
-O |
ReleaseSafe |
Zig optimize mode. ReleaseSafe keeps bounds and overflow checks, which become Go panics. |
-export |
Only functions whose names start with this prefix become Go functions | |
-trim |
Prefix to remove from Zig names, so -trim ct_ turns ct_walk into Walk |
|
-lib |
lib/*.a |
Build mode: the static library the build installs, as a pattern under its prefix |
-stack |
1M |
The size of the stacks the library runs on, such as 256K or 8M. They take up memory only as they are used. |
-lc |
off | For single files: allow libc's C headers and std.c. Whether zigo links libc depends only on what the library uses. |
-platforms |
all four | Comma-separated platforms to build for, such as linux,darwin/arm64. Use it for a library that does not support them all. |
-add |
Build mode: a Zig file to add to the library, such as one with streams | |
-D |
Build mode: an option for zig build, such as -D simd=false. Repeatable. |
|
-mode |
auto |
How wrappers call Zig: auto uses the fast path for functions zigo proves bounded, regular never does, fast always does |
-fast |
Comma-separated patterns of Zig function names to always call through the fast path | |
-stats |
Write the build's time and peak memory, per step, as JSON to this file | |
-keep |
Keep the intermediate build files |
Every generated Go file starts with the zigo and Zig versions that produced it, such as // Code generated by zigo 0.1.0 with Zig 0.17.1 from walk.zig. DO NOT EDIT., so a diff after upgrading either one is easy to explain.
A regular call tells Go's scheduler that the goroutine is busy outside Go, the way cgo and system calls do, so other goroutines and the garbage collector carry on during it. That handoff is most of a call's cost. A fast call skips it: the goroutine is pinned to its processor and runs Zig on that processor's stack, like a Go assembly function.
| Linux arm64 | macOS arm64 | |
|---|---|---|
| zigo, fast | 6.1 ns | 6.0 ns |
| cgo | 15 ns | 15 ns |
| zigo, regular | 19 ns | 19 ns |
Those are for one goroutine. With 12 calling at once, on 16 cores, regular calls took 28–31 ns on Linux, and cgo's 23–27 ns.
During a fast call the goroutine cannot be preempted, and a garbage collection waits for it to finish, so it suits only functions that return within microseconds and never block.
By default (-mode auto), zigo decides by analyzing each function's machine code, for each platform. If only some platforms can use the fast path, the generated code chooses with a constant, which costs nothing. zigo uses the fast path only for functions it proves bounded: nothing they can reach loops, recurses, makes a system call, calls or jumps through a pointer, or waits, and they can run at most 2,000 instructions, including in the functions they call. Code that jumps backward is not a loop unless it can repeat. A switch can use a jump table, if zigo can prove everywhere that it goes: it tracks what each register can hold, to find the table and how many entries it has. Anything the analysis cannot decode or does not recognize counts as unbounded, so it may miss bounded functions, but must never pass an unbounded one. Each generated call says which path it takes and why:
func CountEntries(path string) int64 {
// Regular path: on linux/amd64, it calls basic.countDir, which is
// unbounded: it makes a system call.
zigoR := zigoLib.Call2(__zigo__.Fn_count_entries, ...)The analysis is tested two ways: hand-assembled code exercising each of its rules on both architectures, and examples/fastmode, Zig functions named for what they really are (bounded_*, unbounded_*, or maybe_* for known misses), which a test checks the analysis against on each platform. For the jump tables, other tests change each thing that the proof needs, and compare which registers it thinks each instruction changes with Go's disassembler, for millions of random ones. For libghostty-vt it picks 70 of 209 functions, and for SQLite 42 of 276.
Some functions look quick, but are not safe to pick. Many of SQLite's simplest ones, such as sqlite3_changes, can wait for a lock. Ghostty's _new and _free functions call the allocator they are given. Functions that read a string or a list take longer for longer ones.
-fast forces the fast path for functions you know are short, and zigo warns about any it could not prove. Hand-written code can also choose per call: the Ghostty example writes small buffers through the fast path and large ones through the regular one. Libraries with threadlocal variables take the regular path for fast calls on Linux amd64, where swapping the thread pointer means blocking signals.
| Package | What it is |
|---|---|
github.com/sprisa/zigo |
The zigo command |
github.com/sprisa/zigo/zig |
The source of the runtime that each library gets a copy of, and zigo.zig, the Zig module every library is built with. Generated code does not import it. |
github.com/sprisa/zigo/sqlite |
SQLite without cgo, in a Go module of its own |
github.com/sprisa/zigo/examples/... |
Examples, which are also the test suite's subjects |
A package with a zigo library works in any Go program, as any other dependency does, including when it is vendored. (If you move the package to another import path, run go generate again.) It needs no Zig, C compiler, libc or zigo, and does not depend on which versions of zigo other packages use.
That is because each library has its own copy of zigo's runtime. An image and its runtime must agree on details such as how a Zig stack is laid out, down to the byte. If packages shared one runtime, Go would choose its newest version for all of them, whichever version of zigo had built their images. Instead, zigo writes both at once, from one definition of that layout. examples/portable tests libraries with different layouts running together in one program.
To upgrade a library to a new version of zigo, run go generate again.
Copies cost little. Each has 42 KB of source for a typical library. Thread-locals add 16 KB, and streams 7 KB, but only to libraries that use them, as with the code for setting up libc. In a program, each adds 10–13 KB, and its library's calls have their own stacks.
Since every library has its own types, what they have in common does not depend on them:
- Every library's panics have the same method.
- Every library's
ErrUnsupportediserrors.ErrUnsupported, as far aserrors.Isis concerned.
Exported functions take up to six registers' worth of arguments. zigo.String and zigo.Slice take two each.
| Zig | Go |
|---|---|
u8 … u64, i8 … i64 |
uint8 … uint64, int8 … int64 |
usize, isize |
uint, int |
bool |
bool |
enum(u8) and other sized enums |
The matching integer, signed if any value is negative |
*T, [*]T, ?*T for integer, bool or float T |
*T |
Other pointers, such as *anyopaque |
unsafe.Pointer |
C typedefs of any of these, such as int64_t |
The same as the type itself |
zigo.String |
string. Zig must not write to it. |
zigo.Slice(T), zigo.Bytes |
[]T, []byte |
f32, f64 |
float32, float64 |
extern struct by value |
A generated struct with the same fields. Pointers in it are unsafe.Pointer, and can point to Go memory. |
packed struct(u16), and other structs of one integer |
The integer |
extern union by value |
A generated type, with a method for each member that returns a pointer to it, such as *v.Active() = Coordinate{X: 1} |
Results can be any of these except zigo.String and zigo.Slice. Pointer results are returned as uintptr, since they point into Zig memory. Functions can have any number of parameters.
zigo skips functions it cannot call correctly, and lists them with the reason at the top of zigo.go. These have:
- A large struct or union as a Zig function's result. These are returned in memory, and Zig's debug info says that such functions return nothing, so zigo does not know the type. It finds these functions by their machine code. Return the value through a pointer parameter instead. C functions can return them.
- A struct with bit-fields, its own alignment, SIMD vectors, or fields packed closer together than usual. Pass a pointer to it.
- A union with pointers, which Go's garbage collector would not see.
- A layout that depends on the platform. Optimized builds do not always have the debug info to check this.
- On macOS arm64, a Zig
packed structof less than 64 bits that could be passed on the stack, because there are many parameters. There, other structs of one integer are passed differently, and one whose field is calledbitslooks the same in Zig's debug info. - A
va_list, which Go cannot make, or a 16, 80 or 128-bit float.
Calls with floats, with structs, or that need more than 6 registers go through an adapter. This is a small function zigo generates and compiles, which takes the values in a way zigo can pass, and makes the real call. So a compiler applies each platform's rules for passing values, rather than zigo. Functions compiled by Zig have adapters in Zig, and others in C, because the two do not always agree. For example, on arm64, Zig 0.17 passes struct { a: [2][2]f32 } differently from what C's rules say. If a call only needs an adapter for its floats, it allocates nothing. Otherwise, it allocates one block of Go memory for its parameters and result. On an M4 Max, a call with a float took 11 ns, and one with a small struct 50 ns. examples/byvalue tests these with C and Zig.
zigo reads signatures from a Debug build of the library, because debug info from optimized code can leave out parameters. The images themselves are built with -O.
Zig must not keep a pointer to Go memory after the call returns. zigo keeps arguments alive and in place for the duration of the call, and moves any buffer that would live on a goroutine stack to the heap, because goroutine stacks can move.
A call from Go costs 6–20 ns, which adds up when there is one or more for each row. Instead, zigo can make the loop over the rows run in Zig, and pass many rows in each call. A library asks for this in its Zig code. There is no flag, and libraries that do not use it generate the same code as before.
zigo.stream makes a Go iterator from a Zig one, which is any type whose next function returns ?Row or !?Row:
const User = struct { id: i64, name: []const u8, active: bool };
const Users = struct {
// ...
pub fn next(self: *Users) !?User {
// ...
}
};
comptime {
zigo.stream("users", Users, .{});
}zigo generates a Go struct, User, and this function. context is the *Users, which a function of your own can make, as examples/streams does:
func Users(context unsafe.Pointer) iter.Seq2[User, error]It is an iter.Seq[User] if next cannot fail. An error ends the rows, after the ones before it. It is an Error with its name in Zig, so errors.Is(err, lib.Error("OutOfMemory")) finds it.
zigo.forEach does the opposite: it makes a Go function that calls a Zig one for each row of a Go iterator. The Zig function's parameters are a pointer and a row, and it returns void or !void:
comptime {
zigo.forEach("add_users", Users.add, .{}); // fn add(self: *Users, user: User) !void
}n, err := lib.AddUsers(users, slices.Values(list))It stops at the first row that fails. n is how many succeeded, so it is also that row's index. If the Zig function cannot fail, the Go one returns nothing.
Rows are structs of integers of 8, 16, 32 or 64 bits, bool, f32, f64, enums with such an integer type, and []const u8, which is a Go string. Streams' rows can also have []u8 and [:0]const u8. Anything else is a compile error that says which field. Zig checks that an enum's value from Go is one it has, and panics if not.
Some things differ from a call for each row:
- Streams read ahead. A batch has up to 64 rows. The first has one, and they grow while they are quick, so slow rows still arrive soon after Zig returns them.
.{ .max_rows = 1 }never reads ahead. Use it ifnextcan wait for something, such as input, or if what it does must happen in step with Go's loop. - After a loop stops early, continue with the same iterator. Another loop over it starts at the next row. Another call to
Usersmakes a new iterator, which misses any rows the first had read ahead. - Bulk input waits for more rows. Zig gets them 64 at a time, or sooner once they have 64 KiB of text, and at the end. So Go can have produced rows after one that fails, which are not used. If the Go iterator panics, those that Zig has not had are dropped.
.{ .max_rows = 1 }passes each on its own. - A panic in
nextcan lose rows that came before it in the same batch. After one, using the iterator again panics too. - Text is safe to keep. A stream copies it once, when
nextreturns the row, or before any of your Go code runs again, so it only needs to stay valid until then. A batch's strings share one block of memory, usually up to 64 KiB, which stays as long as any of them does. To keep only a few, usestrings.Clone. Bulk input copies nothing: Zig reads Go's strings, and must not keep them after it returns. - Batches always take the regular path, whatever
-modeand-fastsay, since they can take a while.
Time per row on Linux arm64, for rows without text:
| Batches | max_rows = 1 |
|
|---|---|---|
zigo.stream, 1,000 rows |
4.3 ns | 31 ns |
zigo.forEach, 1,000 rows |
3.4 ns | 29 ns |
A stream of only one row takes about 250 ns, most of it to make the iterator and find that there are no more rows. For that, use an ordinary function.
A project with a build.zig cannot import zigo. Instead, -add compiles a Zig file with zigo's module, and links it with the project's library. The file can declare the library's C functions as extern fn, and use them in streams. Its own export fns become Go functions too, whatever -export says. This needs no changes to the project, and works for C libraries:
//go:generate go run github.com/sprisa/zigo -export ghostty_ -trim ghostty_ -add cells.zig .examples/ghostty/cells.zig uses this to read a terminal's cells. For each one, its text and colors take four calls to libghostty-vt. Reading an 80 by 24 screen takes 188 µs with those calls from Go, and 27 µs with a stream.
A panic in the added file becomes a Go panic, but without the Zig functions on the stack.
Go runs Zig code inside its own process and threads, so the library has to fit in:
- libc works, within limits. On Linux, zigo links it only if the library needs it, and reports any function that nothing provides. On macOS, it is the system's.
- No threads. Get parallelism by calling Zig from several goroutines. libc's
pthread_createfails withENOSYS. threadlocalvariables last for one call. Each call starts with their initial values, so they work for per-thread caches and hints, such asstd.heap.smp_allocator's, but not for state that must outlast a call.- No callbacks into Go. Use batch or iterator-style APIs: Zig fills a buffer and returns, and Go calls again to continue. For many rows, streams do that for you.
- Global variables work. Zig may be running on several goroutines at once, so protect shared globals with atomics or
std.Thread.Mutex, as in any threaded program. - Vtables work.
std.mem.Allocator,std.Io.Writer,std.fmtand other code that stores function pointers in data are fine.
zigo installs its own panic handler and std_options in the root module it builds, so library code needs nothing special. Import zigo only for zigo.String, zigo.Slice, and streams.
zigo supports macOS 13 and later, on Apple silicon and Intel. Most libraries need no changes. Some things differ from Linux:
- The system's libSystem is libc. Every macOS program uses it, even without cgo, so binaries are not fully static. zigo finds the functions that a library uses when it loads it. If that version of macOS does not have one, the first call panics with its name. Libraries cannot use other system libraries or frameworks.
- Libraries must use libSystem for system calls. Zig compiles code that uses
std.os.linuxfor macOS without an error, but its system calls would be different ones there. zigo reports an error if a library makes system calls itself. Usestd.c, C functions, or other parts ofstd. - Programs with the hardened runtime, which Apple requires to notarize them, need the entitlement
com.apple.security.cs.allow-unsigned-executable-memory. zigo loads code into memory, which is not signed. Without it, on Apple silicon, macOS kills the program at its first call. The program cannot catch this or print an error: the crash report saysCode Signature Invalid.com.apple.security.cs.allow-jitis not enough. Programs thatgo buildmakes do not use the hardened runtime. This has not been tested on Intel Macs. - C code's environment is the one the program started with. Without cgo,
os.Setenvdoes not change it. - Nothing can start threads, as on Linux. That includes
pthread_create, but zigo does not check for other ways, such as Grand Central Dispatch. Code must not use them. - Overflowing a Zig stack crashes with
SIGBUS, rather thanSIGSEGV.
If a library does not support macOS, use -platforms linux. On macOS, its package still compiles, and zigoLib.Available() returns false.
This section is about libc on Linux. On macOS, libSystem is libc. There, zigo also turns abort, exit and failed asserts into Go panics, makes pthread_create fail, and stops if C code uses the functions that would break Go's runtime.
After compiling a library, zigo checks whether it uses functions that nothing in it provides. If so, zigo links the parts it needs of musl, a libc whose source comes with Zig. The program is still one static binary, and building it still needs only Go. sqlite uses libc for 66 functions, and libghostty-vt, with SIMD off, for none.
libc normally keeps each thread's data, such as errno, where the CPU's thread pointer says, but that register belongs to Go's runtime. zigo changes the one function per architecture musl reads it with to find the data from the stack pointer instead, at the end of the Zig stack. So each call has its own errno, and calls cost the same as without libc. If a Zig update changes that function, zigo stops with an error. After linking, it also decodes the library's machine code, and stops if anything that should not use the thread pointer does.
Some things differ from a normal program:
- Functions that would end or signal the process become Go panics:
abort,exit,_exit,raiseand failedasserts. The call is abandoned where it was, so a mutex it held stays locked. - Some functions are build errors, because they would break Go's runtime: starting processes (
fork,system,posix_spawn), changing signal handling (sigaction,sigprocmask), changing users (setuid), and acting on threads (pthread_exit,pthread_kill). Use Go for these. zigo checks for calls to libc functions by name, not for system calls the library makes itself. - Data kept per thread does not reliably last between calls, since each can run on a different stack. That includes
errnoandpthread_setspecificvalues. Destructors for those never run. - A mutex must be unlocked by the call that locked it.
- Constructors run before the first call. Destructors and
atexitfunctions never run, and output left in aFILE's buffer when the program exits is lost, so usefflush. - The environment is a copy of Go's from the first call. Later changes in Go do not reach C, or the other way around.
mallocis zigo's own, in zig/libc/malloc.zig. It scales across cores, and keeps freed blocks of up to 8 MiB for reuse: at most 32 MiB of large ones, plus 2 MiB for each CPU. Small blocks are never returned to the kernel.- Each library has its own libc, so memory one library allocates must be freed by the same library.
Building musl takes about 8 seconds per platform, once for each Zig version and -stack size. examples/libc tests the main parts of this.
musl is under the MIT license, whose notice programs that include it must carry.
On Linux, Zig 0.17's memcmp, bcmp, strlen, memchr, strcspn and strspn work a byte at a time, and its strcspn first measures the whole string, so searching a long string for each match takes quadratic time. zigo links its own versions instead, from zig/memory.zig, into every Linux library that uses them, with or without libc. On macOS, libraries use libSystem's, which are already fast. They compare or search up to 16 bytes at a time, with instructions every amd64 and arm64 CPU has. If your library defines one of these functions itself, its own version is used.
A Zig panic becomes a Go panic, which you can recover. Its value is a pointer to the package's own Panic type, with the message and the Zig functions on the stack:
panic: zig: index out of bounds: index 5, len 3
zig stack:
basic.lookup
basic.zig:91
goroutine 1 [running]:
github.com/sprisa/zigo/examples/basic/__zigo__/zig.(*Library).call(0x18bc98, 0x11c74, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0)
/src/examples/basic/__zigo__/zig/call_native.go:42 +0x164
github.com/sprisa/zigo/examples/basic/__zigo__/zig.(*Library).Call1(...)
/src/examples/basic/__zigo__/zig/call.go:13
github.com/sprisa/zigo/examples/basic.Lookup(...)
/src/examples/basic/zigo.go:73
main.main()
/src/main.go:5 +0x44
To find a panic from any zigo library, without importing it, look for the method they all have:
defer func() {
err, _ := recover().(error)
var p interface{ error; ZigoPanic() string }
if errors.As(err, &p) {
log.Print(p.ZigoPanic()) // index out of bounds: index 5, len 3
}
}()The panicking Zig call is abandoned. Memory and globals stay valid, but anything the call held, such as an open file, is not released. Functions the compiler inlined appear as the function they were inlined into.
Crashes are reported too. A segfault inside Zig, including a stack overflow against the guard page below each Zig stack, gets Go's normal crash report with every goroutine's stack.
The usual ways to call native code from Go all fall short of a single static binary without cgo:
- cgo needs a C toolchain for every target, and the system linker.
- purego loads a shared library at run time. On Linux that needs libc, so the binary is no longer static.
- Translating to Go, as
modernc.org/sqlitedoes with C, cannot handle Zig's generated C well, and the result is several times slower.
zigo splits the job into two parts.
Building, with Zig. zigo compiles the library for each platform and links it with Zig's bundled linker into a position-independent executable that needs no interpreter. Linking resolves every address except the absolute pointers stored in data, such as vtables, which the linker lists for later. zigo packs the memory image, that list, and tables of function names and source lines into one file, and generates the Go code that uses it, including a copy of the runtime.
For macOS, Zig's own linker makes a Mach-O dynamic library, and zigo turns it into the same kind of image. Its pointers to libSystem become another table in the file. Its debug info is in the object files it was linked from, so zigo works out where the linker moved each function.
Running, with Go's runtime. On the first call, zigo maps memory, copies the image in, adds the load address to each absolute pointer, and makes the code executable, the way a dynamic loader would. On macOS, it also sets the pointers to libSystem, which it finds with dlsym. Each call then:
- Takes a Zig stack, of 1 MiB unless
-stacksays otherwise, from a pool, which keeps a spare one for each processor so that parallel calls do not contend. The stacks are mapped outside Go's heap, with a guard region below each. Each is in a slot aligned to its size, 2 MiB for a 1 MiB stack, so code running on a stack can find its end from the stack pointer. - Calls
runtime.entersyscall, the hook Go uses around its own system calls, so the scheduler and garbage collector carry on while Zig runs. - Runs a short assembly routine, the call routine. It writes a panic record at the top of the Zig stack, switches to that stack, puts the arguments where Zig expects them, and calls the function.
- Calls
runtime.exitsyscalland returns the result.
On a panic, zigo's handler finds the panic record from the stack pointer, saves the message and the return addresses it finds by following frame pointers, restores Go's registers and jumps back into the call routine, which returns to Go with a panic flag set. Go then panics with the decoded message and stack.
Signals are not blocked during calls. Go's signal handler needs to find the current goroutine: on amd64 it reads the per-thread data the FS register points to, which Zig code without threadlocal variables never touches, and on arm64 it reads register x28, which zigo builds Zig never to use. On macOS, the handler always finds the goroutine through the thread pointer, so libSystem can use x28. After a panic, zigo restores it.
CPU features. On Linux, Zig's standard library reads the page size, CPU features and the vDSO through getauxval, which libc would provide. zigo provides it from the Go process's own values, so code that picks an implementation by CPU feature sees the real ones, and clocks are read through the vDSO without a system call. Values that point into the Go binary, such as its program headers, are left out.
Thread-locals. On Linux, a library with threadlocal variables needs the thread pointer, the register (FS on amd64, TPIDR_EL0 on arm64) through which each thread finds its own copy of them, and which Go's runtime also uses. For each call, zigo sets up a fresh block with the variables' initial values at the top of the Zig stack, and the call routine points the thread pointer at it, restoring Go's afterwards, panic or not. Go's signal handler reads the thread pointer on amd64, and on arm64 in programs that use cgo, so there zigo blocks signals during the call, which costs two system calls. On macOS, code finds these variables by calling a function, so zigo provides one that finds the block from the stack pointer. Calls leave the thread pointer and signals alone, so thread-locals only add about 2 ns to a call.
Measured on Linux arm64 (Docker on Apple silicon), calling a function that adds two integers:
| Per call | Allocations | |
|---|---|---|
| Plain Go function | 0.9 ns | 0 |
| cgo | 15 ns | 0 |
| zigo | 19 ns | 0 |
Calling a function that adds two integers through the fast path takes 6.1 ns.
Writing a line of terminal output to libghostty-vt, built the same way (ReleaseSafe, SIMD off):
| Per write | |
|---|---|
| go-libghostty, through cgo | 374–421 ns |
| examples/ghostty, through zigo | 362 ns, using the fast path |
Zig's vectors (@Vector, std.simd) compile to NEON, SSE and AVX instructions in the image like any other code. zigo builds for each architecture's baseline CPU, which includes NEON on arm64 but only SSE2 on amd64.
libghostty-vt's simd option is a different matter: it adds the C++ libraries simdutf and Highway. The example leaves it off. zigo can now link the libc they need, but has not been tried with C++.
zigo reports each build's time and peak memory, and -stats writes them per step as JSON. TestExamplesUpToDate fails if building an example takes more memory than its budget, and on GitHub Actions adds each example's build time and peak memory to the job summary.
| Example | Cold | Warm |
|---|---|---|
| basic | 15 s, 431 MiB (builds compiler-rt once) | 0.7 s |
| libc | 16 s, 347 MiB (builds libc once, with compiler-rt already built) | 0.8 s |
| ghostty | 188 s, 1.6 GiB on Linux (downloads and builds Ghostty five times) | 3.5 s |
| portable | 15 s, 345 MiB (builds libc once for its larger stacks, with compiler-rt already built) | 0.6 s |
| byvalue | 17 s, 399 MiB on macOS; 66 s, 1.7 GiB on Linux | 1.5 s |
| modules | 60 s, 1.7 GiB on Linux (46 s of it for Zig to compile its build system, once) | 0.9 s on macOS |
| sqlite | 70 s, 1 GiB on macOS (builds SQLite five times) | 1.3 s |
Zig's cache does most of the work on later runs. zigo keeps compiler-rt, libc, its own Zig sources and the program that reads modules from build.zig in its directory under the user cache directory, so Zig can reuse them. Zig's cache for code that zigo compiles itself is there too, unless ZIG_LOCAL_CACHE_DIR says otherwise.
Memory use is close to cgo's. Zig's stacks are not part of Go's heap, so they don't affect when the garbage collector runs. During a 5-second Zig call, the longest garbage collection pause measured was under 50 ms.
- zigo's runtime links to Go runtime internals:
runtime.entersyscall,runtime.exitsyscall,runtime.procPin,runtime.procUnpin, on Linuxruntime.getAuxv, and on Linux arm64, for libraries with thread-locals,runtime.iscgo. They are not a public API, but widely used packages such as gvisor and purego depend on them, and the Go team has promised not to change them (go.dev/issue/67401). A future Go release could still need a zigo update, and libraries generated again with it. - The call routines are hand-written assembly, one per architecture.
- Tested with Zig 0.17.1 and Go 1.26–1.27.
| Example | What it shows |
|---|---|
| basic | Every supported type, globals, vtables, panics, system calls, a stack overflow |
| streams | Streams and bulk input, with a log parser |
| threadlocal | threadlocal variables and std.heap.smp_allocator |
| fastmode | Ground truth for the boundedness analysis that picks fast calls |
| libc | libc from a single Zig file: errno, mutexes, streams, constructors, malloc, and what becomes a panic |
| modules | A library that imports modules from its build.zig, and a panic in one |
| portable | Larger stacks, and libraries with different runtimes in one program |
| byvalue | Floats, structs and unions by value, and many parameters, in C and Zig |
| ghostty | libghostty-vt, an existing Zig project built with its own build.zig, with all 209 of its C API functions, and a stream of a screen's cells from an added Zig file. readme/main.go is go-libghostty's README example with only the import changed, and a test builds it with CGO_ENABLED=0, checks the binary is static, and runs it. |
go generate ./examples/... # needs Zig
go test -timeout 30m ./... # also regenerates every example and checks it is up to date
(cd sqlite/lib && go generate) && (cd sqlite && go test ./...) # SQLite, a module of its ownEach example is also a test suite: its tests call the Zig library and check the results, the Go runtime's behavior during calls, and panics. TestExamplesUpToDate regenerates every example, and SQLite, the way its go:generate line does and compares the output with the committed files, so a change to the generator shows up as a diff. CI runs everything on amd64 and arm64 Linux, without cgo and with the race detector, and runs the tests that call Zig on macOS too, on arm64 and, with Rosetta, amd64.
The tests that call Zig skip on unsupported platforms. They run on macOS and Linux. On macOS, run the Linux ones in a container, and those for Intel Macs with Rosetta:
docker run --rm -v "$PWD":/src -w /src golang:1.27 go test ./...
GOARCH=amd64 CGO_ENABLED=0 go test ./examples/...