🎓 A1Learner
🔍
0 of 55 lessons completed

Zig Structs

A struct is a custom type that groups related values into one value. It lets a point, a person, or a book be held under a single name.

Define a struct and read its fields

This program defines a Point type with two fields. It then prints each field on its own.

const std = @import("std");
const Point = struct { x: i32, y: i32 };

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const p = Point{ .x = 2, .y = 5 };
    try out.print("{d} {d}\n", .{ p.x, p.y });
}

Change a field of a var struct

A struct made with var can have its fields changed. The new y value replaces the old one.

const std = @import("std");
const Point = struct { x: i32, y: i32 };

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    var p = Point{ .x = 1, .y = 3 };
    p.y = 8;
    try out.print("{d} {d}\n", .{ p.x, p.y });
}

Hold different types in one struct

Fields do not all need the same type. This book holds a string and a number.

const std = @import("std");
const Book = struct { title: []const u8, pages: i32 };

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const b = Book{ .title = "Dune", .pages = 412 };
    try out.print("{s} {d}\n", .{ b.title, b.pages });
}

Example

const std = @import("std");
const Rect = struct { width: i32, height: i32 };

fn area(r: Rect) i32 {
    return r.width * r.height;
}

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const r = Rect{ .width = 4, .height = 6 };
    try out.print("{d} {d} {d}\n", .{ r.width, r.height, area(r) });
}

Key points

  • Struct: A struct groups related values under one type name.
  • Field: A field is one named value inside a struct.
  • Create: Point{ .x = 2, .y = 5 } makes a point with those field values.
  • Access: Use a dot to read a field, as in p.x.
  • Change: A field of a var struct can be changed with an assignment like p.y = 8.

In this example, Rect groups a width of 4 and a height of 6 into one value. The area function reads both fields from that value and returns 24, which main prints after the two fields.

Note

In Zig, assigning a struct copies the whole value to the new variable.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does p.y print after const p = Point{ .x = 3, .y = 4 }; ?