Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Types and Memory

Structs

Learn Zig structs: declaring fields, default values, initialization with .{}, methods and self, init and deinit conventions, nested and anonymous structs, tuples and the @This builtin.

Structs are Zig's way of grouping data. There are no classes, no inheritance, no constructors and no access modifiers on fields. A struct is a collection of fields plus optional declarations (functions and constants) inside its namespace. That is all, and surprisingly little else is needed.

Declaring and creating structs

A struct type is a value, so you give it a name with const:

ZIG
const std = @import("std");

const Point = struct {
    x: f32,
    y: f32,
};

pub fn main() void {
    const origin = Point{ .x = 0, .y = 0 };
    var p: Point = .{ .x = 3, .y = 4 };      // type inferred from the left side

    p.x += 1;
    std.debug.print("origin ({d}, {d}), p ({d}, {d})\n", .{ origin.x, origin.y, p.x, p.y });
}
TEXT
origin (0, 0), p (4, 4)

Fields are initialized with .name = value, in any order, and every field must be set unless it has a default. A leading . with no type name (.{ ... }) is an anonymous literal that takes its type from the context.

Default field values

ZIG
const Config = struct {
    host: []const u8 = "localhost",
    port: u16 = 8080,
    verbose: bool = false,
};

const c = Config{ .port = 9000 };
// c.host == "localhost", c.port == 9000, c.verbose == false

Default values make configuration structs pleasant: pass only what differs. They are the Zig replacement for named and default arguments.

Methods

A function declared inside a struct is a method if its first parameter is the struct (or a pointer to it). You call it with dot syntax; the value before the dot becomes the first argument:

ZIG
const Rectangle = struct {
    width: f32,
    height: f32,

    fn area(self: Rectangle) f32 {
        return self.width * self.height;
    }

    fn scale(self: *Rectangle, factor: f32) void {
        self.width *= factor;
        self.height *= factor;
    }
};

pub fn main() void {
    var r = Rectangle{ .width = 3, .height = 4 };
    std.debug.print("area {d}\n", .{r.area()});
    r.scale(2);
    std.debug.print("area {d}\n", .{r.area()});
}
TEXT
area 12
area 48

self is just a parameter name by convention. Use self: T to read, and self: *T to modify. The call r.scale(2) automatically takes the address of r, which is why r must be a var. The same function can also be called as Rectangle.scale(&r, 2): methods are ordinary functions in the struct's namespace.

Namespaced declarations

A struct can hold constants and functions that do not take self:

ZIG
const Circle = struct {
    radius: f64,

    const pi = 3.14159;

    fn init(radius: f64) Circle {
        return .{ .radius = radius };
    }

    fn area(self: Circle) f64 {
        return pi * self.radius * self.radius;
    }
};

// Circle.init(2).area()

Circle.init(2.0) is a plain function call that returns a Circle. The name init is only a convention, but it is a strong one: init builds a value, and deinit releases whatever it owns (memory, files). A type that owns heap memory usually takes an allocator in init and offers deinit, and callers pair them with defer x.deinit().

Nested, anonymous and packed forms

Structs can nest and be written inline:

ZIG
const Player = struct {
    name: []const u8,
    position: struct { x: i32, y: i32 } = .{ .x = 0, .y = 0 },
    inventory: [3]?u32 = [_]?u32{null} ** 3,
};

An anonymous struct literal with no type is a quick record:

ZIG
const record = .{ .id = 7, .label = "seven" };
std.debug.print("{d} {s}\n", .{ record.id, record.label });

A struct whose fields have no names is a tuple; it is what the arguments of std.debug.print are:

ZIG
const pair = .{ 42, "answer" };
std.debug.print("{d} {s} {d}\n", .{ pair[0], pair[1], pair.len });

Tuples are indexed with [0], [1], and have a .len. They are useful for returning several values.

@This and self-referencing types

Inside a struct, @This() is the struct's own type. Generic data structures use it to refer to themselves without knowing their name:

ZIG
const Node = struct {
    value: i32,
    next: ?*@This() = null,
};

A node holds an optional pointer to another node. (?*Node works too inside a named struct.) Structs cannot contain themselves by value, because their size would be infinite; they contain pointers instead.

Copying and comparing

Assigning a struct copies all fields (shallow). Pointers inside are copied as pointers. There is no == for structs; compare fields yourself, or use std.meta.eql(a, b) for simple types and std.testing.expectEqual in tests.

Struct layout

Zig does not promise a particular field order or padding for a plain struct; the compiler may reorder fields to save space. If you need C layout, write extern struct. If you need bit-level packing, write packed struct. Both are explained in the memory layout lesson.

Stand-ins you can run

C structs and functions taking a struct pointer map one-to-one to Zig's Rectangle, including default-like initialization through an init function.

C Stand-in (C): struct, methods as functions, init

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Rust Stand-in (Rust): structs with methods, defaults and tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you create a Point with x = 1 and y = 2?

    Zig struct literals name each field with a leading dot.
  2. 2. What makes a function inside a struct a method you can call with dot syntax?

    Dot call syntax passes the value before the dot as the first parameter.
  3. 3. Why must r be var to call r.scale(2) when scale takes self: *Rectangle?

    Only a var can provide a mutable pointer; a const value gives *const.
  4. 4. What is a tuple in Zig?

    Tuples are anonymous structs with unnamed fields.
  5. 5. What does @This() return inside a struct?

    It names the innermost enclosing type, handy for self-referencing generic types.

Summary

  • Structs group fields; create them with .{ .field = value }; defaults replace named arguments.
  • Methods are ordinary functions whose first parameter is the struct (self: T reads, self: *T writes).
  • init and deinit are conventions for building and releasing values; pair with defer.
  • Anonymous structs and tuples give quick records and multi-value returns.
  • Plain structs have unspecified layout; use extern or packed when layout matters.

Next: Enums and Unions