Zig Opaque Types
Some libraries give you a handle: a pointer to something you’re allowed to pass around and hand back, but not to look inside. C is full of these. fopen gives you a FILE *, SQLite gives you a sqlite3 *, a window library gives you a GLFWwindow *. The library knows what’s in there, and you’re not supposed to care. Zig describes such a type with opaque {}: a type whose size and fields are unknown, so the only thing you can have is a pointer to it. This is a short lesson. You’ll mostly meet opaque types when you work with C, and they’re simpler than they sound.
Declaring an opaque type
Section titled “Declaring an opaque type”You write opaque {} where you’d write struct { ... }, but with no fields:
const std = @import("std");
const Database = opaque {};
fn describe(db: *Database) void { _ = db; std.debug.print("got a database handle\n", .{});}
pub fn main() void { std.debug.print("a pointer to it is {d} bytes\n", .{@sizeOf(*Database)}); _ = describe;}Output:
a pointer to it is 8 bytesDatabase is a real, new type, but Zig knows nothing about what’s inside it. What you can have is a pointer to it, *Database, and a pointer always has a known size (8 bytes on a 64-bit machine). Functions can take and return those pointers. _ = describe; only stops Zig from complaining that the function is unused; you’ll see real handles in a moment. The language reference on opaque is short and worth a look.
What you can’t do with one
Section titled “What you can’t do with one”Because Zig doesn’t know the size or the fields, almost everything else is off limits. You can’t make a value of the type:
const Database = opaque {};
pub fn main() void { var db: Database = undefined; _ = &db;}main.zig:4:13: error: non-extern variable with opaque type 'main.Database' var db: Database = undefined; ^~~~~~~~And you can’t ask for its size: @sizeOf(Database) fails with no size available for uninstantiable type 'main.Database'. You can’t copy what a pointer points at either, db.* gives cannot load opaque type. That’s the whole idea. You can hold the handle, but the insides belong to the library.
Why bother? Type safety
Section titled “Why bother? Type safety”Why not just use one generic pointer for every handle? Because then nothing stops you from passing a font where a window was expected. Every opaque {} is its own type, so Zig catches the mix-up:
const Window = opaque {};const Font = opaque {};
fn closeWindow(w: *Window) void { _ = w;}
fn useFont(f: *Font) void { closeWindow(f);}
pub fn main() void { useFont(undefined);}main.zig:9:17: error: expected type '*main.Window', found '*main.Font' closeWindow(f); ^main.zig:9:17: note: pointer type child 'main.Font' cannot cast into pointer type child 'main.Window'Both are “a pointer to something I can’t see”, and yet they can’t be confused. In C, many libraries use a plain void * for handles, and this mistake compiles fine there.
A real example: C’s FILE
Section titled “A real example: C’s FILE”Here’s an opaque type doing its actual job. C’s standard library has fopen, fputs and fclose, which work with a FILE *. We tell Zig that FILE is opaque and declare the three C functions with extern:
const std = @import("std");
const FILE = opaque {};
extern "c" fn fopen(path: [*:0]const u8, mode: [*:0]const u8) ?*FILE;extern "c" fn fputs(text: [*:0]const u8, file: *FILE) c_int;extern "c" fn fclose(file: *FILE) c_int;
pub fn main() void { const file = fopen("hello.txt", "w") orelse { std.debug.print("could not open hello.txt\n", .{}); return; }; defer _ = fclose(file);
_ = fputs("Hello from C's stdio!\n", file); std.debug.print("wrote hello.txt\n", .{});}Calling C functions needs C’s standard library, so run it with -lc:
zig run main.zig -lccat hello.txtYou’ll see:
wrote hello.txtHello from C's stdio!Without -lc, Zig stops with error: dependency on libc must be explicitly specified in the build command. Let’s walk through the new parts:
extern "c" fndeclares a function that lives in C’s library, not in your Zig code.[*:0]const u8is a C string: a pointer to bytes ending in a zero. String literals turn into it for you. See Zig Sentinel-Terminated Types.fopenreturns?*FILE: aFILEpointer, ornullif it failed.orelsehandles thenullcase; that’s Zig Optionals.c_intis C’sint. We throw the results away with_ =to keep the example short; real code would check them.
The important line for this lesson is const FILE = opaque {};. We never say what’s inside a FILE, and we never need to. We get a *FILE from fopen, pass it to fputs, and hand it back to fclose. That’s exactly how you’d use it in C.
Opaque types can have methods
Section titled “Opaque types can have methods”An opaque {} can hold declarations, just like a struct: constants, types and functions. That means you can give a handle a nice method-style API. Here a small Zig “library” hides its real data behind an opaque Counter:
const std = @import("std");
const Counter = opaque { const State = struct { count: u32, step: u32, };
pub fn create(gpa: std.mem.Allocator, step: u32) !*Counter { const s = try gpa.create(State); s.* = .{ .count = 0, .step = step }; return @ptrCast(s); }
pub fn destroy(self: *Counter, gpa: std.mem.Allocator) void { gpa.destroy(self.inner()); }
pub fn tick(self: *Counter) void { const s = self.inner(); s.count += s.step; }
pub fn value(self: *Counter) u32 { return self.inner().count; }
fn inner(self: *Counter) *State { return @ptrCast(@alignCast(self)); }};
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
const counter = try Counter.create(gpa, 5); defer counter.destroy(gpa);
counter.tick(); counter.tick(); std.debug.print("value: {d}\n", .{counter.value()});}Output:
value: 10The code that uses Counter only ever sees *Counter and its four pub methods. Inside, create allocates the real State and returns its address disguised as a *Counter with @ptrCast. The private inner method turns it back. @alignCast is needed on the way back because Zig doesn’t know how an opaque type is aligned in memory; it checks the alignment in Debug builds. gpa.create and gpa.destroy allocate and free one value; they’re explained in Zig Allocators.
Let’s be honest about this one: in pure Zig code you rarely need it. Zig has no private fields, so this trick is one way to stop users from poking at your data. But most Zig libraries just use a normal struct and document which fields not to touch. You’ll see the pattern mostly where Zig code is shared with C, because a C caller can’t know a Zig struct’s layout anyway.
*anyopaque: C’s void *
Section titled “*anyopaque: C’s void *”Zig has one built-in opaque type, anyopaque. A *anyopaque is a pointer to “anything at all”, like void * in C. Any single-item pointer turns into one automatically (a *const T becomes a *const anyopaque), and you turn it back with @ptrCast and @alignCast when you know what it really is. It’s how you pass a “context” through code that doesn’t know your types, such as a C callback:
const std = @import("std");
fn repeat(times: u32, context: *anyopaque, action: *const fn (*anyopaque) void) void { for (0..times) |_| action(context);}
fn addOne(context: *anyopaque) void { const total: *u32 = @ptrCast(@alignCast(context)); total.* += 1;}
pub fn main() void { var total: u32 = 0; repeat(3, &total, addOne); std.debug.print("total: {d}\n", .{total});}Output:
total: 3repeat doesn’t know or care what context points to; it passes it along. Only addOne knows it’s really a *u32. The *const fn (*anyopaque) void parameter is a pointer to a function; see Zig Function Pointers.
This is also how Zig’s own allocator works. std.mem.Allocator is a struct with a ptr: *anyopaque field (the allocator’s state, whatever kind it is) and a table of functions that know how to use it. You’ll see the same shape in Zig Interfaces.
Practice
Section titled “Practice”1. Which lines fail?
Section titled “1. Which lines fail?”Given const Image = opaque {};, decide which of these compile. Then check by trying each one in a small program.
const a: *Image = undefined; // Aconst b: ?*Image = null; // Bvar c: Image = undefined; // Cconst d = @sizeOf(Image); // Dconst e = @sizeOf(*Image); // EHint: pointers to an opaque type are fine. Anything that needs the type’s size or a value of it isn’t.
Show solution
A, B and E compile. C fails with non-extern variable with opaque type, and D with no size available for uninstantiable type. A pointer (or an optional pointer, which can be null) only stores an address, so its size is known. The opaque type itself has no known size.
2. Reset the counter
Section titled “2. Reset the counter”Add a pub fn reset(self: *Counter) void method to the opaque Counter from this page, and use it: tick twice, reset, tick once, print the value.
Hint: the new method looks like tick: get the real state with self.inner() and change it.
Show solution
const std = @import("std");
const Counter = opaque { const State = struct { count: u32, step: u32, };
pub fn create(gpa: std.mem.Allocator, step: u32) !*Counter { const s = try gpa.create(State); s.* = .{ .count = 0, .step = step }; return @ptrCast(s); }
pub fn destroy(self: *Counter, gpa: std.mem.Allocator) void { gpa.destroy(self.inner()); }
pub fn tick(self: *Counter) void { const s = self.inner(); s.count += s.step; }
pub fn reset(self: *Counter) void { self.inner().count = 0; }
pub fn value(self: *Counter) u32 { return self.inner().count; }
fn inner(self: *Counter) *State { return @ptrCast(@alignCast(self)); }};
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const counter = try Counter.create(gpa, 5); defer counter.destroy(gpa);
counter.tick(); counter.tick(); counter.reset(); counter.tick(); std.debug.print("value: {d}\n", .{counter.value()});}Output:
value: 5Users of Counter get the new feature without ever seeing State. That’s the benefit of the handle: the inside can change freely.
3. Collect into a context
Section titled “3. Collect into a context”Using the repeat function from the anyopaque section, write an action that doubles a u64 each time it’s called. Start at 1, repeat 10 times, and print the result.
Hint: cast the context to *u64 with @ptrCast(@alignCast(context)), then x.* *= 2.
Show solution
const std = @import("std");
fn repeat(times: u32, context: *anyopaque, action: *const fn (*anyopaque) void) void { for (0..times) |_| action(context);}
fn double(context: *anyopaque) void { const x: *u64 = @ptrCast(@alignCast(context)); x.* *= 2;}
pub fn main() void { var x: u64 = 1; repeat(10, &x, double); std.debug.print("result: {d}\n", .{x});}Output:
result: 1024repeat works unchanged with a u64 instead of a u32, because it never looks at what context points to. Only double knows, and it has to get the type right.
opaque {}declares a type with an unknown size and layout; you can only use pointers to it.- You can’t create a value, take its
@sizeOf, or read what a pointer points at. - Each opaque type is distinct, so Zig stops you from mixing up handles like
*Windowand*Font. - C handles like
FILE *become*FILEwithconst FILE = opaque {};; calling libc needs-lc. - An opaque type can hold methods, which gives handles a tidy API.
*anyopaqueis C’svoid *; get the real pointer back with@ptrCast(@alignCast(p)), carefully.
Next up: Zig Memory Basics, the stack, the heap, and why Zig makes you choose.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: opaque: the official definition, with the type-safety example.
- Zig language reference: @ptrCast: converting between pointer types, and what it does not check.
- Zig 0.17.0 release notes: C translation moving to the translate-c package.
- Zig standard library source: Allocator.zig: a real interface built on
ptr: *anyopaque.