Zig Structs
A struct groups related values into one type. A point has an x and a y; a book has a title, an author and a page count. Structs are the main way to model data in Zig, and as you saw in the Syntax lesson, every Zig file is itself a struct.
Defining and creating a struct
const std = @import("std");
const Book = struct {
title: []const u8,
author: []const u8,
pages: u32,
};
pub fn main() void {
const novel = Book{
.title = "The Long River",
.author = "M. Tran",
.pages = 412,
};
std.debug.print("{s} by {s}, {d} pages\n", .{ novel.title, novel.author, novel.pages });
}The Long River by M. Tran, 412 pages
Fields are declared as name: Type, and set with .name = value. Every field must be given a value (or have a default), otherwise the code does not compile.
Changing fields
A struct stored in a var can have its fields changed; one stored in a const cannot:
const std = @import("std");
const Counter = struct {
label: []const u8,
count: u32,
};
pub fn main() void {
var clicks = Counter{ .label = "clicks", .count = 0 };
clicks.count += 1;
clicks.count += 1;
std.debug.print("{s}: {d}\n", .{ clicks.label, clicks.count });
// structs are values: assignment copies
var copy = clicks;
copy.count = 100;
std.debug.print("original {d}, copy {d}\n", .{ clicks.count, copy.count });
}clicks: 2
original 2, copy 100
Default field values
Fields can have defaults. Then they may be left out when creating the struct:
const std = @import("std");
const Settings = struct {
volume: u8 = 50,
muted: bool = false,
theme: []const u8 = "light",
};
pub fn main() void {
const defaults = Settings{};
const custom = Settings{ .theme = "dark", .volume = 80 };
std.debug.print("{any}\n", .{defaults});
std.debug.print("{d} {} {s}\n", .{ custom.volume, custom.muted, custom.theme });
}.{ .volume = 50, .muted = false, .theme = { 108, 105, 103, 104, 116 } }
80 false dark
{any} prints the whole struct, but shows strings as byte lists — print string fields with {s} yourself for friendlier output.
Anonymous struct literals
When the type is already known from context, you can drop the type name and write just .{ … }. This is extremely common: in function arguments, return statements and arrays.
const std = @import("std");
const Point = struct { x: i32, y: i32 };
fn manhattan(a: Point, b: Point) u32 {
return @abs(a.x - b.x) + @abs(a.y - b.y);
}
pub fn main() void {
const route = [_]Point{ .{ .x = 0, .y = 0 }, .{ .x = 3, .y = 4 }, .{ .x = -1, .y = 6 } };
var total: u32 = 0;
for (route[0 .. route.len - 1], route[1..]) |from, to| {
total += manhattan(from, to);
}
std.debug.print("distance travelled: {d}\n", .{total});
std.debug.print("one hop: {d}\n", .{manhattan(.{ .x = 1, .y = 1 }, .{ .x = 4, .y = 5 })});
}distance travelled: 13
one hop: 7
Nested structs and arrays of structs
Fields can be other structs, arrays or slices:
const std = @import("std");
const Address = struct { city: []const u8, zip: []const u8 };
const Customer = struct {
name: []const u8,
address: Address,
orders: u32 = 0,
};
pub fn main() void {
var customers = [_]Customer{
.{ .name = "Hoa", .address = .{ .city = "Da Nang", .zip = "550000" } },
.{ .name = "Karl", .address = .{ .city = "Graz", .zip = "8010" }, .orders = 3 },
};
customers[0].orders += 1;
for (customers) |c| {
std.debug.print("{s} ({s} {s}) - {d} order(s)\n", .{ c.name, c.address.zip, c.address.city, c.orders });
}
}Hoa (550000 Da Nang) - 1 order(s)
Karl (8010 Graz) - 3 order(s)
Tuples
A struct without field names is a tuple. You have been using them all along: .{ a, b } in std.debug.print. Elements are accessed by index:
const pair = .{ "age", 42 };
// pair[0] is "age", pair[1] is 42, pair.len is 2Memory layout
A normal struct lets the compiler reorder fields for the best packing. When the exact layout matters, use extern struct (C-compatible layout) or packed struct (fields squeezed together bit by bit, e.g. for hardware registers or flags).
| Kind | Layout |
|---|---|
struct |
chosen by the compiler |
extern struct |
same as C, in declaration order |
packed struct |
bit-exact, no padding |
Test yourself
How do you set the pages field when creating a struct?
- pages: 10
- .pages = 10
- pages = 10
- this.pages = 10
What happens if you leave out a field that has no default value?
- It becomes 0
- It becomes undefined
- Compile error: missing struct field
- It becomes null
After var b = a; with structs, changing b.x …
- also changes
a.x - changes only
b - is a compile error
- frees
a