Zig Anonymous Structs & Tuples
You’ve typed .{ ... } in every single print call so far: std.debug.print("{d}\n", .{x});. It’s time to find out what that actually is. It’s a tuple: a struct whose fields have no names, only positions. Its cousin is the anonymous struct, a struct with named fields but no type name. Both are quick ways to bundle a few values together without defining a type first. They’re great for short jobs, like passing arguments to print or returning two values from a function, and this page also shows where they stop being a good idea.
Anonymous struct literals
Section titled “Anonymous struct literals”In Zig Structs you wrote .{ .x = 1, .y = 2 } where Zig knew the type, like const p: Point = .{ ... }. If there’s no type to go on, Zig doesn’t give up. It invents a new struct type on the spot, with exactly those fields:
const std = @import("std");
pub fn main() void { const person = .{ .name = "Ana", .age = 30 };
std.debug.print("{s} is {d}\n", .{ person.name, person.age });}Output:
Ana is 30person has a struct type with a name and an age field, but that type has no name you could write down. You use its fields like any struct’s. The reference calls these anonymous struct literals.
A neat use is the named placeholders you met in Zig Format Strings. print accepts an anonymous struct, and {[name]s} picks a field by its name:
const std = @import("std");
pub fn main() void { std.debug.print("{[name]s} has {[points]d} points\n", .{ .name = "Bo", .points = 42 });}Output:
Bo has 42 pointsTuples: fields with numbers instead of names
Section titled “Tuples: fields with numbers instead of names”Leave out the field names, and you get a tuple. The fields are numbered from 0, and you read them with [ ], like an array:
const std = @import("std");
pub fn main() void { const item = .{ "apple", 3, true };
std.debug.print("name: {s}\n", .{item[0]}); std.debug.print("count: {d}\n", .{item[1]}); std.debug.print("in stock: {}\n", .{item[2]}); std.debug.print("fields: {d}\n", .{item.len});}Output:
name: applecount: 3in stock: truefields: 3Unlike an array, a tuple’s items can all have different types: here a string, a number and a bool. It still has a .len, though. And now the print mystery is solved: the second argument of print is a tuple of the values to fill in, in order. .{} is an empty tuple, for when there’s nothing to fill in. The language reference on tuples has the full rules.
The index must be known while compiling
Section titled “The index must be known while compiling”Each field of a tuple can have a different type, so Zig has to know which field you mean while it compiles the program. An index that’s only known when the program runs doesn’t work:
const std = @import("std");
pub fn main() void { const item = .{ "apple", 3, true }; var i: usize = 0; _ = &i; std.debug.print("{any}\n", .{item[i]});}main.zig:7:39: error: unable to resolve comptime value std.debug.print("{any}\n", .{item[i]}); ^main.zig:7:39: note: tuple field index must be comptime-knownThink about it from Zig’s side: if i could be 0 or 1, the result would be a string or a number, and Zig needs one type. Literal indexes like item[0] are always fine. (The _ = &i; line just stops Zig from complaining that i is never changed.)
Looping over a tuple: inline for
Section titled “Looping over a tuple: inline for”The same rule means a normal for loop doesn’t work on a tuple either. You get the same tuple field index must be comptime-known error. Use inline for instead. It unrolls the loop while compiling: Zig writes out the loop body once for each field, so each copy knows its field’s type:
const std = @import("std");
pub fn main() void { const values = .{ 42, "hello", 2.5, false };
inline for (values, 0..) |value, i| { std.debug.print("{d}: {s}\n", .{ i, @typeName(@TypeOf(value)) }); }}Output:
0: comptime_int1: *const [5:0]u82: comptime_float3: boolEach pass through the body gets a value of a different type, and @TypeOf(value) shows which. You won’t need inline for often in everyday code, but it’s how print itself walks through your arguments. There’s more about running code while compiling in Zig Comptime.
Tuple types: returning several values
Section titled “Tuple types: returning several values”A tuple type is written like a struct with types but no names: struct { i32, i32 }. That’s the clean way to return more than one value from a function:
const std = @import("std");
fn minMax(numbers: []const i32) struct { i32, i32 } { var low = numbers[0]; var high = numbers[0]; for (numbers) |n| { if (n < low) low = n; if (n > high) high = n; } return .{ low, high };}
pub fn main() void { const temps = [_]i32{ 12, -3, 25, 8 }; const result = minMax(&temps); std.debug.print("coldest {d}, warmest {d}\n", .{ result[0], result[1] });}Output:
coldest -3, warmest 25The function says it returns struct { i32, i32 }, so return .{ low, high }; knows what to build. &temps turns the array into a slice for the parameter; see Zig Slices.
Destructuring: unpacking a tuple
Section titled “Destructuring: unpacking a tuple”Reading result[0] and result[1] works, but it’s nicer to give each value a name right away. That’s destructuring:
const std = @import("std");
fn divmod(a: u32, b: u32) struct { u32, u32 } { return .{ a / b, a % b };}
pub fn main() void { const quotient, const remainder = divmod(17, 5); std.debug.print("17 / 5 = {d} remainder {d}\n", .{ quotient, remainder });
const name, _, const city = .{ "Ana", 30, "Lisbon" }; std.debug.print("{s} lives in {s}\n", .{ name, city });}Output:
17 / 5 = 3 remainder 2Ana lives in LisbonPut one const (or var) per value on the left, separated by commas. Use _ for a value you don’t need. If you’ve used Python’s q, r = divmod(17, 5) or JavaScript’s const [q, r] = ..., it’s the same idea. Destructuring works on arrays too: const first, const second = [2]u8{ 4, 5 };.
Joining tuples and turning them into arrays
Section titled “Joining tuples and turning them into arrays”Two more things tuples can do. ++ joins two tuples into a longer one, as long as both are known while compiling. And a tuple whose items all fit one type turns into an array when that’s the result type:
const std = @import("std");
pub fn main() void { const first = .{ 1, 2 }; const both = first ++ .{ 3, 4 }; std.debug.print("{d} fields\n", .{both.len});
const numbers: [4]i32 = both; std.debug.print("{any}\n", .{numbers});}Output:
4 fields{ 1, 2, 3, 4 }That conversion is also why const arr: [3]i32 = .{ 1, 2, 3 }; works: the .{ ... } starts out tuple-shaped and becomes an array because the type says so. Note that **, which used to repeat a tuple or array, was removed in Zig 0.17. To fill an array with one value, write const zeros: [8]u8 = @splat(0);.
When to use which
Section titled “When to use which”A quick guide, since you now have three ways to group values:
| You want | Use |
|---|---|
Arguments for print |
a tuple: .{ a, b } |
| To return two or three values from a function | a tuple type: struct { u32, u32 }, then destructure |
| A one-off group passed straight to a function | an anonymous struct: .{ .name = ..., .points = ... } |
| Data you store, change or pass around a lot | a named struct with field names and a type name |
Tuples and anonymous structs are handy, but they don’t document anything. result[1] says much less than result.warmest. Once a group of values shows up in more than one place, give it a name.
Practice
Section titled “Practice”1. Rectangle facts
Section titled “1. Rectangle facts”Write a function rectInfo(w: u32, h: u32) that returns a tuple with the area and the perimeter. Destructure the result and print both.
Hint: the return type is struct { u32, u32 }, and the caller writes const area, const perimeter = rectInfo(3, 4);.
Show solution
const std = @import("std");
fn rectInfo(w: u32, h: u32) struct { u32, u32 } { return .{ w * h, 2 * (w + h) };}
pub fn main() void { const area, const perimeter = rectInfo(3, 4); std.debug.print("area {d}, perimeter {d}\n", .{ area, perimeter });}Output:
area 12, perimeter 14The tuple only lives long enough to be unpacked, which is exactly what tuples are good at.
2. Describe every value
Section titled “2. Describe every value”Given the tuple .{ 7, "seven", 7.0, true }, print each value on its own line together with its position, like 0: 7. Use {any} for the values.
Hint: a plain for won’t work on a tuple. inline for (t, 0..) |value, i| will.
Show solution
const std = @import("std");
pub fn main() void { const t = .{ 7, "seven", 7.0, true }; inline for (t, 0..) |value, i| { std.debug.print("{d}: {any}\n", .{ i, value }); }}Output:
0: 71: { 115, 101, 118, 101, 110 }2: 73: trueThe string shows up as bytes because {any} doesn’t know it’s text. To print it properly you’d need {s}, but in a loop over mixed types one placeholder has to fit every value, which is another hint that tuples are best kept small and simple.
3. Fix the counter
Section titled “3. Fix the counter”This program tries to count with an anonymous struct and doesn’t build. Fix it by giving the struct a name.
const std = @import("std");
pub fn main() void { var stats = .{ .wins = 0, .losses = 0 }; stats.wins += 1; stats.wins += 1; stats.losses += 1; std.debug.print("{d} wins, {d} losses\n", .{ stats.wins, stats.losses });}Hint: define const Stats = struct { ... }; with two u32 fields, and annotate the variable with it.
Show solution
const std = @import("std");
const Stats = struct { wins: u32 = 0, losses: u32 = 0,};
pub fn main() void { var stats: Stats = .{}; stats.wins += 1; stats.wins += 1; stats.losses += 1; std.debug.print("{d} wins, {d} losses\n", .{ stats.wins, stats.losses });}Output:
2 wins, 1 lossesWith a real type, the fields are ordinary u32 values you can change. Default values even let you write .{} to start at zero.
.{ .a = 1, .b = 2 }without a known type is an anonymous struct: Zig makes up a type with those fields..{ 1, "a", true }is a tuple: fields by position, read witht[0], with a.len.print’s arguments are a tuple.- A tuple index must be known while compiling; loop over a tuple with
inline for. - Return several values with a tuple type like
struct { u32, u32 }, then destructure:const q, const r = divmod(17, 5);. - Don’t swap with
a, b = .{ b, a };: it gives the wrong result. Usestd.mem.swap. ++joins tuples. The**operator was removed in Zig 0.17 (use@splat).- Anonymous struct fields from compile-time values are frozen; for data you change, use a named struct.
Next up: Zig Packed & Extern Structs, for when you need to control exactly how a struct sits in memory.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: tuples: indexing,
.len,++andinline for. - Zig language reference: destructuring tuples: returning several values and unpacking them.
- Zig language reference: anonymous struct literals:
.{ ... }with and without a result type. - Zig 0.17.0 release notes: the removal of
**and its@splatreplacement.