Skip to content

Zig Reflection

Imagine you want one function that prints any struct, field by field, or one that fills a settings struct from lines like width=120, without writing a line of code per field. To do that, your code has to ask a type questions: “what fields do you have, and what are their types?” That’s reflection. In Python or Java, reflection happens while the program runs. In Zig it happens at compile time, with a few @ builtins, so it costs nothing at run time. This page uses the Zig 0.17 form of @typeInfo, which changed from earlier versions, so be careful when you copy older examples from the web.

You’ve used these two already. @TypeOf(x) gives the type of a value, and @typeName(T) turns a type into text:

const std = @import("std");
const Point = struct { x: i32, y: i32 };
pub fn main() void {
const p: Point = .{ .x = 1, .y = 2 };
const name = "zig";
const T = @TypeOf(p);
std.debug.print("{s}\n", .{@typeName(T)});
std.debug.print("{s}\n", .{@typeName(@TypeOf(name))});
std.debug.print("{s}\n", .{@typeName(@TypeOf(p.x))});
std.debug.print("{}\n", .{T == Point});
}

Output:

main.Point
*const [3:0]u8
i32
true

const T = @TypeOf(p); stores a type in a constant, and you can compare types with ==. A string literal’s real type is a pointer to a fixed-size array with a zero at the end (see Zig Sentinels). That’s the kind of thing @typeName is good for finding out.

@typeInfo(T) returns a description of the type T. The description is a tagged union called std.lang.Type: first it tells you what kind of type it is (an integer, a float, a struct, a pointer…), and then the details for that kind. Print just the kind with {t}:

const std = @import("std");
const Point = struct { x: i32, y: i32 };
pub fn main() void {
inline for (.{ u8, i32, f64, bool, []const u8, ?u16, [3]u8, Point }) |T| {
std.debug.print("{s:<12} {t}\n", .{ @typeName(T), @typeInfo(T) });
}
}

Output:

u8 int
i32 int
f64 float
bool bool
[]const u8 pointer
?u16 optional
[3]u8 array
main.Point struct

{s:<12} pads the name to 12 characters so the columns line up. Because it’s a tagged union, you read the details with switch and a capture, like any other tagged union (see Zig Tagged Unions):

const std = @import("std");
fn describe(comptime T: type) void {
switch (@typeInfo(T)) {
.int => |info| std.debug.print("{s}: {t} integer, {d} bits\n", .{ @typeName(T), info.signedness, info.bits }),
.float => |info| std.debug.print("{s}: float, {d} bits\n", .{ @typeName(T), info.bits }),
.array => |info| std.debug.print("{s}: {d} items of {s}\n", .{ @typeName(T), info.len, @typeName(info.child) }),
.optional => |info| std.debug.print("{s}: maybe a {s}\n", .{ @typeName(T), @typeName(info.child) }),
else => std.debug.print("{s}: something else\n", .{@typeName(T)}),
}
}
pub fn main() void {
describe(u8);
describe(i64);
describe(f32);
describe([4]bool);
describe(?u16);
describe(void);
}

Output:

u8: unsigned integer, 8 bits
i64: signed integer, 64 bits
f32: float, 32 bits
[4]bool: 4 items of bool
?u16: maybe a u16
void: something else

The kinds are named in lowercase. A few of them, like struct, enum, union and fn, are Zig keywords, so you write them with the @"..." syntax: .@"struct", .@"enum". It looks odd, but it just means “a name that happens to be a keyword”. The full list of kinds and their details lives in the standard library file lib/std/lang.zig, under pub const Type.

Here’s the “print any struct” function. For a struct, @typeInfo(T).@"struct" has two lists that line up: field_names and field_types. Loop over both together with inline for:

const std = @import("std");
const Config = struct {
name: []const u8,
port: u16,
debug: bool,
ratio: f32 = 0.5,
};
fn printStruct(value: anytype) void {
const T = @TypeOf(value);
const info = @typeInfo(T).@"struct";
std.debug.print("{s}:\n", .{@typeName(T)});
inline for (info.field_names, info.field_types) |name, FieldType| {
const field_value = @field(value, name);
if (FieldType == []const u8) {
std.debug.print(" {s} = \"{s}\"\n", .{ name, field_value });
} else {
std.debug.print(" {s} = {any} ({s})\n", .{ name, field_value, @typeName(FieldType) });
}
}
}
pub fn main() void {
const cfg: Config = .{ .name = "server", .port = 8080, .debug = true };
printStruct(cfg);
}

Output:

main.Config:
name = "server"
port = 8080 (u16)
debug = true (bool)
ratio = 0.5 (f32)

Line by line:

  • @typeInfo(T).@"struct" takes the struct details. If T isn’t a struct, that’s a compile error.
  • inline for (info.field_names, info.field_types) |name, FieldType| walks both lists at the same time. It must be inline, because each round has a different field type, and types only exist while compiling (you saw this in Zig Inline Functions).
  • @field(value, name) reads the field whose name is the string name. It’s the same as value.port, but with the name chosen at compile time.
  • if (FieldType == []const u8) picks how to print strings. Since FieldType is known while compiling, each copy of the loop body keeps only one branch.

Add a field to Config and printStruct picks it up without any change. That’s the point of reflection.

@field works on the left side of = too. That makes the settings parser from the intro short. This program takes name=value pairs and stores each one in the matching field of Settings:

const std = @import("std");
const Settings = struct {
width: u32 = 80,
height: u32 = 24,
volume: u8 = 5,
};
fn set(settings: *Settings, key: []const u8, text: []const u8) !void {
const info = @typeInfo(Settings).@"struct";
inline for (info.field_names, info.field_types) |name, T| {
if (std.mem.eql(u8, key, name)) {
@field(settings, name) = try std.fmt.parseInt(T, text, 10);
return;
}
}
return error.UnknownSetting;
}
pub fn main() void {
var s: Settings = .{};
const lines = [_][2][]const u8{
.{ "width", "120" },
.{ "volume", "9" },
.{ "colour", "red" },
.{ "volume", "300" },
};
for (lines) |line| {
set(&s, line[0], line[1]) catch |err| {
std.debug.print("{s}={s}: {t}\n", .{ line[0], line[1], err });
continue;
};
std.debug.print("{s}={s}: ok\n", .{ line[0], line[1] });
}
std.debug.print("{any}\n", .{s});
}

Output:

width=120: ok
volume=9: ok
colour=red: UnknownSetting
volume=300: Overflow
.{ .width = 120, .height = 24, .volume = 9 }

Notice the mix of compile time and run time. The key comes in while the program runs, so Zig can’t pick the field in advance. Instead, inline for writes out one if per field: “if the key is width, parse a u32 into width”, and so on. At run time, those ifs check the key one by one. Each one calls parseInt with the right type, so volume=300 fails with Overflow, because 300 doesn’t fit in a u8.

Sometimes you only need a yes or no: does this type have a field, or a declaration (a constant or function inside it), with this name?

const std = @import("std");
const Player = struct {
name: []const u8,
score: u32,
pub fn reset(self: *Player) void {
self.score = 0;
}
const max_score = 100;
};
pub fn main() void {
std.debug.print("field name: {}\n", .{@hasField(Player, "name")});
std.debug.print("field level: {}\n", .{@hasField(Player, "level")});
std.debug.print("decl reset: {}\n", .{@hasDecl(Player, "reset")});
std.debug.print("decl max_score: {}\n", .{@hasDecl(Player, "max_score")});
std.debug.print("score is a {s}\n", .{@typeName(@FieldType(Player, "score"))});
}

Output:

field name: true
field level: false
decl reset: true
decl max_score: false
score is a u32

max_score is there, so why false? Since Zig 0.17, @hasDecl only sees pub declarations, wherever you call it from. reset is pub, max_score isn’t. Older code may rely on the old behavior, so it’s good to know. (The struct info’s decl_names list also only has the pub ones.) @FieldType(T, "name") gives the type of one field, which is handy for generic code that copies or parses a single field.

These are the building blocks of checks like std.meta.hasMethod, which you used in Zig Generic Functions to give callers a clear error.

Enums have their own info, with field_names and field_values (the numbers behind each name). Here’s a menu that lists every color, plus the standard library’s stringToEnum for the other direction:

const std = @import("std");
const Color = enum { red, green, blue };
pub fn main() void {
const info = @typeInfo(Color).@"enum";
std.debug.print("Color has {d} values:\n", .{info.field_names.len});
inline for (info.field_names, info.field_values) |name, value| {
std.debug.print(" {d}: {s}\n", .{ value, name });
}
std.debug.print("{any}\n", .{std.meta.stringToEnum(Color, "green")});
std.debug.print("{any}\n", .{std.meta.stringToEnum(Color, "pink")});
}

Output:

Color has 3 values:
0: red
1: green
2: blue
.green
null

The loop has to be inline again: field_values holds comptime_ints, numbers that only exist while compiling. std.meta.stringToEnum turns text into an enum value, or null if no value has that name. It’s built from the same @typeInfo you just used. For a single value, @tagName(c) from Zig Enums is still the quick way to get its name.

Struct info also has field_attrs, a third list that lines up with the other two. Each item can tell you the field’s default value:

const std = @import("std");
const Settings = struct {
width: u32 = 80,
title: []const u8 = "untitled",
volume: u8,
};
pub fn main() void {
const info = @typeInfo(Settings).@"struct";
inline for (info.field_names, info.field_types, info.field_attrs) |name, T, attrs| {
if (attrs.defaultValue(T)) |default| {
if (T == []const u8) {
std.debug.print("{s} defaults to \"{s}\"\n", .{ name, default });
} else {
std.debug.print("{s} defaults to {any}\n", .{ name, default });
}
} else {
std.debug.print("{s} has no default\n", .{name});
}
}
}

Output:

width defaults to 80
title defaults to "untitled"
volume has no default

attrs.defaultValue(T) returns an optional: the default, or null if the field has none. Tools like JSON parsers use this to fill in fields that are missing from the input. The reference on @typeInfo and @field have the official details.

Write fieldCount(comptime T: type) usize that returns how many fields a struct has, and stops the build with fieldCount() needs a struct when T isn’t one. Try it on a struct with three fields.

Hint: check @typeInfo(T) != .@"struct" first. A tagged union can be compared with a tag like this.

Show solution
const std = @import("std");
fn fieldCount(comptime T: type) usize {
if (@typeInfo(T) != .@"struct") @compileError("fieldCount() needs a struct");
return @typeInfo(T).@"struct".field_names.len;
}
const Book = struct { title: []const u8, pages: u32, read: bool };
pub fn main() void {
std.debug.print("Book has {d} fields\n", .{fieldCount(Book)});
}

Output:

Book has 3 fields

Without the check, fieldCount(u32) still fails, but with “access of union field ‘struct’ while field ‘int’ is active”. Your own message is easier to understand.

Write resetNumbers(ptr: anytype) that takes a pointer to any struct and sets every field whose type is u32 to 0, leaving other fields alone. Test it on a struct with a name and two counters.

Hint: ptr is a pointer, so use @TypeOf(ptr.*) to get the struct type, and @field(ptr, name) = 0; to write.

Show solution
const std = @import("std");
const Stats = struct {
name: []const u8,
wins: u32,
losses: u32,
};
fn resetNumbers(ptr: anytype) void {
const info = @typeInfo(@TypeOf(ptr.*)).@"struct";
inline for (info.field_names, info.field_types) |name, T| {
if (T == u32) @field(ptr, name) = 0;
}
}
pub fn main() void {
var s: Stats = .{ .name = "team", .wins = 7, .losses = 3 };
resetNumbers(&s);
std.debug.print("{s}: {d} wins, {d} losses\n", .{ s.name, s.wins, s.losses });
}

Output:

team: 0 wins, 0 losses

@field works through a pointer like normal field access does. The if (T == u32) is decided while compiling, so the name field never even gets an assignment.

Write printHeader(comptime T: type) that prints all field names of a struct on one line, separated by |. For struct { id: u32, name: []const u8, price: f64 } it should print id | name | price.

Hint: a normal for with an index works here, because you only print the names. Print the separator before every name except the first.

Show solution
const std = @import("std");
const Product = struct { id: u32, name: []const u8, price: f64 };
fn printHeader(comptime T: type) void {
const names = @typeInfo(T).@"struct".field_names;
for (names, 0..) |name, i| {
if (i > 0) std.debug.print(" | ", .{});
std.debug.print("{s}", .{name});
}
std.debug.print("\n", .{});
}
pub fn main() void {
printHeader(Product);
}

Output:

id | name | price

The names are plain strings, so they can be stored in the program and looped over at run time. You’d only need inline for if you also used @field or the field types.

  • Reflection in Zig happens at compile time: no run-time cost, and mistakes are compile errors.
  • @TypeOf gives a value’s type, @typeName its name as text, and types compare with ==.
  • @typeInfo(T) returns a tagged union (std.lang.Type): switch on it, or take .@"struct", .@"enum", .int and so on.
  • In 0.17, struct info is lists that line up: field_names, field_types, field_attrs. Old code uses .fields, which no longer exists.
  • Walk fields with inline for (info.field_names, info.field_types) |name, T|, and read or write them with @field(value, name).
  • @hasField checks for a field; @hasDecl only sees pub declarations since 0.17.

Next up: Zig Builtin Functions, a guided tour of the @ functions you’ll meet most.

Quick check

1. In Zig 0.17, how do you loop over a struct's field names and types?
2. What does @field(cfg, "port") mean?
3. A struct has const limit = 10; (not pub). What does @hasDecl(ThatStruct, "limit") return in 0.17?
4. Why do you write .@"struct" instead of .struct when reading @typeInfo?