TExcelTAD
Home › Zig › Zig Methods on Structs

Zig Methods on Structs

Zig has no classes, but a struct can contain functions as well as fields. When a function's first parameter is the struct itself (or a pointer to it), you can call it with dot syntax — point.length() — and it behaves like a method in other languages. There is no hidden this: the receiver is an ordinary, explicitly written parameter, conventionally named self.

A first method

zig · try it yourself
const std = @import("std");

const Rect = struct {
    width: f64,
    height: f64,

    fn area(self: Rect) f64 {
        return self.width * self.height;
    }

    fn isSquare(self: Rect) bool {
        return self.width == self.height;
    }
};

pub fn main() void {
    const r = Rect{ .width = 3, .height = 4.5 };
    std.debug.print("area {d}, square? {}\n", .{ r.area(), r.isSquare() });

    // the dot call is just sugar for:
    std.debug.print("area {d}\n", .{Rect.area(r)});
}
area 13.5, square? false
area 13.5

r.area() and Rect.area(r) are exactly the same call.

Changing the struct: pointer receivers

A by-value self is read-only. A method that modifies the struct takes self: *Rect (a pointer). Zig takes the address automatically when you call it on a var:

zig · try it yourself
const std = @import("std");

const Account = struct {
    owner: []const u8,
    balance: i64 = 0,

    fn deposit(self: *Account, amount: i64) void {
        self.balance += amount;
    }

    fn withdraw(self: *Account, amount: i64) error{InsufficientFunds}!void {
        if (amount > self.balance) return error.InsufficientFunds;
        self.balance -= amount;
    }

    fn report(self: Account) void {
        std.debug.print("{s}: {d}\n", .{ self.owner, self.balance });
    }
};

pub fn main() void {
    var acc = Account{ .owner = "Mai" };
    acc.deposit(500);
    acc.withdraw(120) catch unreachable;
    acc.report();

    acc.withdraw(1000) catch |err| std.debug.print("failed: {t}\n", .{err});
    acc.report();
}
Mai: 380
failed: InsufficientFunds
Mai: 380

Calling a *Account method on a const struct is a compile error — the type system prevents accidental mutation.

Receiver Can modify? Typical use
self: T no getters, calculations
self: *const T no read-only, explicitly by reference
self: *T yes setters, anything that changes state

Constructors: init functions

Zig has no special constructor syntax. By convention, a function named init returns a new instance. Functions without a self parameter are called on the type itself, like static methods:

zig · try it yourself
const std = @import("std");

const Temperature = struct {
    celsius: f64,

    fn init(celsius: f64) Temperature {
        return .{ .celsius = celsius };
    }

    fn fromFahrenheit(f: f64) Temperature {
        return .{ .celsius = (f - 32) * 5 / 9 };
    }

    fn fahrenheit(self: Temperature) f64 {
        return self.celsius * 9 / 5 + 32;
    }
};

pub fn main() void {
    const a = Temperature.init(25);
    const b = Temperature.fromFahrenheit(212);
    std.debug.print("{d}C = {d}F\n", .{ a.celsius, a.fahrenheit() });
    std.debug.print("{d}C = {d}F\n", .{ b.celsius, b.fahrenheit() });
}
25C = 77F
100C = 212F

If the struct owns resources (like heap memory), it usually also has a deinit method that releases them; you will see this pattern with allocators.

@This() and constants inside structs

Inside a struct, @This() refers to the struct type itself. Structs can also hold constants and variables that belong to the type rather than to each instance:

zig · try it yourself
const std = @import("std");

const Vec2 = struct {
    x: f32,
    y: f32,

    const Self = @This();
    const zero = Self{ .x = 0, .y = 0 };

    fn add(a: Self, b: Self) Self {
        return .{ .x = a.x + b.x, .y = a.y + b.y };
    }

    fn scale(self: Self, k: f32) Self {
        return .{ .x = self.x * k, .y = self.y * k };
    }
};

pub fn main() void {
    const v = Vec2.zero.add(.{ .x = 1.5, .y = -2 }).scale(2);
    std.debug.print("({d}, {d})\n", .{ v.x, v.y });
}
(3, -4)

Visibility

Declarations inside a struct are private to the file unless marked pub. When you put a struct in its own file and import it, only its pub fns can be called from outside. Fields, on the other hand, are always accessible.

Custom printing

In Zig 0.15, a struct can control how {f} formats it by defining a format method that takes a *std.Io.Writer:

zig
pub fn format(self: Vec2, writer: *std.Io.Writer) std.Io.Writer.Error!void {
    try writer.print("({d}, {d})", .{ self.x, self.y });
}
// usage: std.debug.print("{f}\n", .{v});

Tip: Keep methods small and give data-changing methods a pointer receiver. If a method doesn't need self at all, it is probably a plain function that can live outside the struct.

Test yourself

What is p.move(1) equivalent to, if p is a Point and move is declared in Point?

  1. move(1)
  2. Point.move(p, 1) (with &p for a pointer receiver)
  3. p->move(1)
  4. this.move(1)

Which receiver type allows a method to modify the struct's fields?

  1. self: T
  2. self: *const T
  3. self: *T
  4. self: ?T

What does @This() return inside a struct definition?

  1. The current instance
  2. The struct type itself
  3. The file name
  4. A pointer to self