Structs in Zig
A kayak struct with field defaults and a method that reads naturally.
const std = @import("std");
const Kayak = struct {
model: []const u8,
length_ft: u32 = 17, // fields can carry defaults
rudder: bool = false,
fn describe(self: Kayak) void {
std.debug.print("{s}: {d} ft, rudder {}\n", .{
self.model, self.length_ft, self.rudder,
});
}
};
pub fn main() void {
const stock = Kayak{ .model = "Petrel" };
const custom = Kayak{ .model = "Auk", .length_ft = 14, .rudder = true };
stock.describe();
custom.describe();
}
How it works
length_ft: u32 = 17gives the field a default; construction fills only.model.- Methods are functions in the struct namespace taking
selffirst. stock.describe()is sugar forKayak.describe(stock)— no hidden this.
Keywords and builtins used here
boolconstfnpubstructu32u8void
The run, in numbers
- Lines
- 20
- Characters to type
- 448
- Tokens
- 131
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 112 seconds.
Step 1 of 3 in Structs & enums, step 13 of 27 in Language basics.