typestar

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

  1. length_ft: u32 = 17 gives the field a default; construction fills only .model.
  2. Methods are functions in the struct namespace taking self first.
  3. stock.describe() is sugar for Kayak.describe(stock) — no hidden this.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Structs & enums, step 13 of 27 in Language basics.

← Previous Next →

Structs in other languages