Zig Struct Defaults
A struct default is a field value written in the struct definition that fills in when a creation omits that field. Defaults let a short creation still produce a complete value.
Use every default
Both fields of Settings have defaults. Creating an empty value fills both fields in.
const std = @import("std");
const Settings = struct { volume: i32 = 50, level: i32 = 1 };
pub fn main() !void {
const out = std.io.getStdOut().writer();
const s = Settings{};
try out.print("{d} {d}\n", .{ s.volume, s.level });
}
Override one default
This creation names only the level field. The volume field keeps its default.
const std = @import("std");
const Settings = struct { volume: i32 = 50, level: i32 = 1 };
pub fn main() !void {
const out = std.io.getStdOut().writer();
const s = Settings{ .level = 3 };
try out.print("{d} {d}\n", .{ s.volume, s.level });
}
Mix a required field with a default
The name field has no default, so the creation gives it. The lives field fills in on its own.
const std = @import("std");
const Player = struct { name: []const u8, lives: i32 = 3 };
pub fn main() !void {
const out = std.io.getStdOut().writer();
const p = Player{ .name = "Ana" };
try out.print("{s} {d}\n", .{ p.name, p.lives });
}
Example
const std = @import("std");
const Item = struct { name: []const u8 = "pen", price: i32 = 5, stock: i32 = 0 };
pub fn main() !void {
const out = std.io.getStdOut().writer();
const a = Item{};
const b = Item{ .stock = 12 };
try out.print("{s} {d} {d}\n", .{ a.name, a.price, a.stock });
try out.print("{s} {d} {d}\n", .{ b.name, b.price, b.stock });
}
Key points
- Default: Write count: i32 = 0 to give a field a starting value.
- Omit: Settings{} uses the default for every field that has one.
- Override: Settings{ .level = 3 } replaces the default for that one field.
- Keep: A field that is not named in a creation keeps its default value.
- Mix: A struct can mix fields with defaults and fields without defaults.
In this example, the first Item uses all three defaults and shows a pen priced at 5 with no stock. The second Item overrides only stock to 12, so its name and price still come from the defaults.
Note
In Zig, a field without a default must be given a value in every creation.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does s.volume print when Settings has volume: i32 = 50 and the code creates const s = Settings{ .level = 3 }; ?