Zig Structs
So far every value you’ve worked with has been one thing: a number, a bool, a string. Real programs deal with things that have several parts. A user has a name and an age, a point has an x and a y, a book has a title, an author and a page count. A struct lets you bundle those parts into one value with its own type name. If you know structs from C or Rust, Zig’s will feel familiar. If you come from Python or JavaScript, think of a class that only holds data (methods come in the next lesson).
Defining a struct
Section titled “Defining a struct”You define a struct with the struct keyword and give it a name with const. Inside the braces you list the fields, each with a name and a type:
const std = @import("std");
const User = struct { name: []const u8, age: u32,};
pub fn main() void { const ana = User{ .name = "Ana", .age = 30 };
std.debug.print("{s} is {d} years old\n", .{ ana.name, ana.age });}Output:
Ana is 30 years oldA few things to notice:
const User = struct { ... };creates a new type calledUser. In Zig, types are values too, so you store them in aconstlike anything else. Type names useTitleCaseby convention.- Fields are separated by commas, and a trailing comma after the last one is normal.
zig fmtkeeps it. User{ .name = "Ana", .age = 30 }creates a value. Each field is written with a dot in front:.name = ....ana.namereads a field. No surprises there.
The language reference on structs has the official version with more examples.
The .{ ... } shorthand
Section titled “The .{ ... } shorthand”You’ll often see a struct value written without its type name, like .{ .name = "Ana", .age = 30 }. That works whenever Zig already knows which type is expected. Zig calls this the result type: the type the value is going to end up as.
const std = @import("std");
const User = struct { name: []const u8, age: u32,};
fn greet(user: User) void { std.debug.print("Hi {s}!\n", .{user.name});}
pub fn main() void { const bo: User = .{ .name = "Bo", .age = 25 }; greet(bo);
greet(.{ .name = "Cy", .age = 41 });}Output:
Hi Bo!Hi Cy!In const bo: User = .{ ... }, the type annotation tells Zig what to build. In greet(.{ ... }), the parameter type does the same job: greet takes a User, so the literal becomes a User. Both forms create exactly the same value. Most Zig code prefers const x: T = .{ ... }, and you’ll see .{} shapes like this all over the standard library. There’s a short lesson on why it works this way in Zig Result Location Semantics.
Every field must be set
Section titled “Every field must be set”Zig won’t fill in missing fields with zeros or nulls. If you forget one, the program doesn’t build:
const Point = struct { x: i32, y: i32,};
pub fn main() void { const p = Point{ .x = 1 }; _ = p;}main.zig:7:20: error: missing struct field: y const p = Point{ .x = 1 }; ~~~~~^~~~~~~~~~main.zig:1:15: note: struct declared hereconst Point = struct { ^~~~~~A typo in a field name is caught the same way. Writing .z = 3 gives error: no field named 'z' in struct 'main.Point'. That’s a nice change from JavaScript, where a misspelled property quietly becomes undefined.
The _ = p; line is there because Zig refuses unused variables. You’ll see it in small examples whenever a value isn’t used.
Default values
Section titled “Default values”A field can have a default value, written after its type with =. Then you can leave it out when you create a value:
const std = @import("std");
const Settings = struct { volume: u8 = 50, muted: bool = false, theme: []const u8 = "light",};
pub fn main() void { const normal: Settings = .{}; const night: Settings = .{ .theme = "dark", .volume = 20 };
std.debug.print("{d} {} {s}\n", .{ normal.volume, normal.muted, normal.theme }); std.debug.print("{d} {} {s}\n", .{ night.volume, night.muted, night.theme });}Output:
50 false light20 false dark.{} means “all the defaults”. In night, the fields you name win and the rest keep their defaults. The order you write them in doesn’t matter: .theme before .volume is fine.
Default values have to be known when the program compiles. A number, a string literal or another constant works. The result of a function that runs while the program runs doesn’t.
Changing a field: const vs var
Section titled “Changing a field: const vs var”Whether you can change a field depends on how you stored the value. A const struct is frozen, fields and all:
const Point = struct { x: i32, y: i32,};
pub fn main() void { const p = Point{ .x = 1, .y = 2 }; p.x = 5;}main.zig:8:6: error: cannot assign to constant p.x = 5; ~^~Use var when you need to change it:
const std = @import("std");
const Point = struct { x: i32, y: i32,};
pub fn main() void { var p = Point{ .x = 1, .y = 2 }; p.x = 5; p.y += 10; std.debug.print("x = {d}, y = {d}\n", .{ p.x, p.y });}Output:
x = 5, y = 12There’s no way to mark a single field as read-only. It’s all or nothing: the whole value is const or the whole value is var.
Assigning makes a copy
Section titled “Assigning makes a copy”This one surprises people coming from Python, JavaScript or Java. In those languages, b = a makes two names for the same object. In Zig, a struct is a plain value, like a number. b = a copies all the fields:
const std = @import("std");
const Point = struct { x: i32, y: i32,};
pub fn main() void { const a = Point{ .x = 1, .y = 2 }; var b = a; b.x = 100;
std.debug.print("a.x = {d}\n", .{a.x}); std.debug.print("b.x = {d}\n", .{b.x});}Output:
a.x = 1b.x = 100Changing b leaves a alone. Same thing when you pass a struct to a function: the function can’t change the caller’s value. If you want two places to share one struct, use a pointer (&a), from Zig Pointers. Through a pointer you still write ptr.x, Zig follows the pointer for you.
Printing a struct
Section titled “Printing a struct”For a quick look while debugging, {any} prints every field:
const std = @import("std");
const Point = struct { x: i32, y: i32,};
const User = struct { name: []const u8, age: u32,};
pub fn main() void { const p = Point{ .x = 3, .y = -4 }; const u = User{ .name = "Ana", .age = 30 }; std.debug.print("{any}\n", .{p}); std.debug.print("{any}\n", .{u});}Output:
.{ .x = 3, .y = -4 }.{ .name = { 65, 110, 97 }, .age = 30 }The point looks great. The user’s name, though, comes out as numbers: {any} doesn’t know that this slice of bytes is meant to be text, so it shows the bytes (A is 65, n is 110, a is 97). For anything a person will read, print the fields yourself with the right placeholders, like {s} for text.
If you print a type often, you can give it a format method and print it with {f}. Here’s what that looks like; methods are explained properly in the next lesson:
const std = @import("std");
const User = struct { name: []const u8, age: u32,
pub fn format(self: User, writer: *std.Io.Writer) std.Io.Writer.Error!void { try writer.print("{s} ({d})", .{ self.name, self.age }); }};
pub fn main() void { const u = User{ .name = "Ana", .age = 30 }; std.debug.print("user: {f}\n", .{u});}Output:
user: Ana (30)The method’s exact shape changed in Zig 0.15, so older tutorials show a longer version that no longer works. All the placeholders, and this trap, are in Zig Format Strings.
Comparing structs
Section titled “Comparing structs”You might expect a == b to compare two structs field by field. Zig doesn’t allow it:
const std = @import("std");
const Point = struct { x: i32, y: i32,};
pub fn main() void { const a = Point{ .x = 1, .y = 2 }; const b = Point{ .x = 1, .y = 2 }; std.debug.print("{}\n", .{a == b});}main.zig:11:33: error: operator == not allowed for type 'main.Point' std.debug.print("{}\n", .{a == b}); ~~^~~~The reason is that “equal” isn’t always obvious. Should two users with the same text in name be equal, even if the text lives in different places in memory? Zig makes you decide. For simple structs, std.meta.eql compares every field for you:
const std = @import("std");
const Point = struct { x: i32, y: i32,};
pub fn main() void { const a = Point{ .x = 1, .y = 2 }; const b = Point{ .x = 1, .y = 2 }; const c = Point{ .x = 9, .y = 2 }; std.debug.print("a and b: {}\n", .{std.meta.eql(a, b)}); std.debug.print("a and c: {}\n", .{std.meta.eql(a, c)});}Output:
a and b: truea and c: falseStructs inside structs, and lists of structs
Section titled “Structs inside structs, and lists of structs”A field can be any type, including another struct or an array. And you can make arrays of structs like arrays of anything else:
const std = @import("std");
const Address = struct { city: []const u8, zip: []const u8,};
const Person = struct { name: []const u8, home: Address,};
pub fn main() void { const people = [_]Person{ .{ .name = "Ana", .home = .{ .city = "Lisbon", .zip = "1100" } }, .{ .name = "Bo", .home = .{ .city = "Oslo", .zip = "0150" } }, };
for (people) |person| { std.debug.print("{s} lives in {s}\n", .{ person.name, person.home.city }); }}Output:
Ana lives in LisbonBo lives in OsloThe result type does a lot of work here. [_]Person{ ... } tells Zig every item is a Person, so each item can be a plain .{ ... }. And because the home field is an Address, its value can be .{ ... } too. You never have to repeat a type name. person.home.city reads through both levels.
Structs can hold constants too
Section titled “Structs can hold constants too”Besides fields, a struct can contain declarations: constants, functions and even other types. They belong to the type, not to each value, and you reach them through the type name:
const std = @import("std");
const Password = struct { pub const min_length = 8;
text: []const u8,};
pub fn main() void { const pw = Password{ .text = "hunter2" }; if (pw.text.len < Password.min_length) { std.debug.print("too short: needs {d} characters\n", .{Password.min_length}); }}Output:
too short: needs 8 charactersmin_length doesn’t take up any room in a Password value; there’s just one of it, on the type. The pub means other files can use it too. Functions declared inside a struct are its methods, which is the next lesson.
Practice
Section titled “Practice”1. A book
Section titled “1. A book”Make a Book struct with a title (text), an author (text) and pages (a u32) that defaults to 100. Create one book with all three fields and one without pages, then print both like Dune by Frank Herbert, 412 pages.
Hint: text fields are []const u8 and print with {s}. A default goes after the type: pages: u32 = 100.
Show solution
const std = @import("std");
const Book = struct { title: []const u8, author: []const u8, pages: u32 = 100,};
pub fn main() void { const books = [_]Book{ .{ .title = "Dune", .author = "Frank Herbert", .pages = 412 }, .{ .title = "Notes", .author = "Me" }, }; for (books) |b| { std.debug.print("{s} by {s}, {d} pages\n", .{ b.title, b.author, b.pages }); }}Output:
Dune by Frank Herbert, 412 pagesNotes by Me, 100 pagesThe second book leaves out .pages, so it gets the default of 100. Putting both books in an array lets one loop print them.
2. Fix the program
Section titled “2. Fix the program”This program won’t build, for two different reasons. Find both and fix them so it prints level 2, 30 hp.
const std = @import("std");
const Player = struct { level: u32, hp: u32,};
pub fn main() void { const player = Player{ .level = 1 }; player.level += 1; std.debug.print("level {d}, {d} hp\n", .{ player.level, player.hp });}Hint: read the first error, fix it, then build again. One problem is about a missing field, the other about changing a value.
Show solution
const std = @import("std");
const Player = struct { level: u32, hp: u32,};
pub fn main() void { var player = Player{ .level = 1, .hp = 30 }; player.level += 1; std.debug.print("level {d}, {d} hp\n", .{ player.level, player.hp });}Output:
level 2, 30 hphp has no default, so it must be set (missing struct field: hp). And player changes, so it has to be var, not const (cannot assign to constant).
3. The oldest person
Section titled “3. The oldest person”Given an array of people with a name and an age, find and print the oldest one.
Hint: keep a copy of the oldest person seen so far in a var, start with the first item, and replace it in a for loop when you find someone older.
Show solution
const std = @import("std");
const Person = struct { name: []const u8, age: u32,};
pub fn main() void { const people = [_]Person{ .{ .name = "Ana", .age = 30 }, .{ .name = "Bo", .age = 67 }, .{ .name = "Cy", .age = 41 }, };
var oldest = people[0]; for (people) |p| { if (p.age > oldest.age) oldest = p; } std.debug.print("oldest: {s} ({d})\n", .{ oldest.name, oldest.age });}Output:
oldest: Bo (67)oldest = p copies the whole struct, which is cheap here (a slice and a number). You could also keep the index of the oldest person instead.
const Name = struct { field: Type, ... };defines a new type;Name{ .field = value }creates a value.- Write
.{ ... }without the type name whenever Zig knows the result type (an annotation or a parameter type). - Every field must be set, unless it has a default value (
volume: u8 = 50)..{}uses all defaults. - A
conststruct can’t change; usevarto change fields. - Assigning or passing a struct copies it. Use a pointer to share one.
{any}prints all fields (text shows as bytes); aformatmethod with{f}prints it your way.==doesn’t work on structs.std.meta.eqldoes, but it compares slices by address, not by text.
Next up: Zig Struct Methods, functions that live inside a struct, self, and @This().
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: struct: the official rules, with methods, empty structs and more.
- Zig language reference: default field values: how defaults work and when not to use them.
- Zig language reference: anonymous struct literals: the
.{ ... }syntax and result types. - Zig in-depth overview: the ideas behind Zig’s design, including no hidden control flow.