Zig Struct Methods
A struct on its own is just data. Most of the time you also want some code that goes with it: work out the area of a rectangle, add money to an account, print a point nicely. In Zig you put those functions inside the struct. That keeps the data and the code that works on it in one place, and lets you call them with a dot, like rect.area(). There are no classes, constructors or inheritance behind this. As you’ll see, a method is just a normal function that happens to live inside a struct.
A function inside a struct
Section titled “A function inside a struct”Anything you declare inside a struct belongs to that struct’s namespace. Functions work the same way as the constants you saw in Zig Structs:
const std = @import("std");
const Rect = struct { width: u32, height: u32,
pub fn square(size: u32) Rect { return .{ .width = size, .height = size }; }};
pub fn main() void { const r = Rect.square(5); std.debug.print("{d} x {d}\n", .{ r.width, r.height });}Output:
5 x 5square is an ordinary function. You call it through the type, Rect.square(5), the same way you’d reach a constant. Its return type is Rect, so .{ ... } in the return knows what to build. Fields and declarations can sit in any order inside the struct, but most code puts the fields first.
Methods and self
Section titled “Methods and self”Now the interesting part. If the first parameter of a function has the struct’s type, you can call it on a value with a dot:
const std = @import("std");
const Rect = struct { width: u32, height: u32,
pub fn area(self: Rect) u32 { return self.width * self.height; }};
pub fn main() void { const r: Rect = .{ .width = 3, .height = 4 };
std.debug.print("area: {d}\n", .{r.area()}); std.debug.print("area: {d}\n", .{Rect.area(r)});}Output:
area: 12area: 12r.area() is just a shorter way to write Rect.area(r). Zig sees that r is a Rect, finds area inside Rect, and passes r as the first argument. Both lines do exactly the same thing.
The name self isn’t a keyword. You could call it rect or r, and you’ll see both in real code. self is the common choice because it reads well. And unlike this in JavaScript or Java, it’s never hidden: if a function wants the value, it says so in its parameter list. The language reference on structs puts it this way: struct methods are not special, they’re only namespaced functions you can call with dot syntax.
Reading vs changing: self: T or self: *T
Section titled “Reading vs changing: self: T or self: *T”Parameters in Zig can’t be changed, and self is a parameter. So this doesn’t build:
const std = @import("std");
const Counter = struct { count: u32 = 0,
pub fn increment(self: Counter) void { self.count += 1; }};
pub fn main() void { var c: Counter = .{}; c.increment(); std.debug.print("{d}\n", .{c.count});}main.zig:7:13: error: cannot assign to constant self.count += 1; ~~~~^~~~~~Even if it did build, it couldn’t work: self would be a copy of c, so changing it would leave c alone. To change the caller’s value, the method needs a pointer to it. Write self: *Counter:
const std = @import("std");
const Counter = struct { count: u32 = 0,
pub fn increment(self: *Counter) void { self.count += 1; }
pub fn get(self: Counter) u32 { return self.count; }};
pub fn main() void { var c: Counter = .{}; c.increment(); c.increment(); std.debug.print("count: {d}\n", .{c.get()});}Output:
count: 2Notice that the call is still c.increment(), not (&c).increment(). Zig takes the address of c for you because the method asks for a pointer. And inside the method you still write self.count, because Zig follows the pointer when you access a field. Pointers are explained in Zig Pointers, but for methods this is all you need.
So the rule of thumb is short:
self: Counterwhen the method only reads.self: *Counterwhen the method changes the value.
@This() and Self
Section titled “@This() and Self”Inside a struct you can write its own name, like Counter above. There’s also a builtin that means “the struct I’m inside”: @This(). Lots of code stores it in a constant called Self:
const std = @import("std");
const Point = struct { x: i32, y: i32,
const Self = @This();
pub fn add(self: Self, other: Self) Self { return .{ .x = self.x + other.x, .y = self.y + other.y }; }};
pub fn main() void { const a: Point = .{ .x = 1, .y = 2 }; const b: Point = .{ .x = 10, .y = 20 }; const c = a.add(b); std.debug.print("({d}, {d})\n", .{ c.x, c.y });}Output:
(11, 22)For a named struct like Point, Self and Point mean the same thing, and using the real name is often clearer. @This() becomes necessary when the struct has no name you can write. That happens with generic types, where a function builds and returns a new struct:
const std = @import("std");
fn Pair(comptime T: type) type { return struct { first: T, second: T,
const Self = @This();
pub fn swapped(self: Self) Self { return .{ .first = self.second, .second = self.first }; } };}
pub fn main() void { const p: Pair(i32) = .{ .first = 1, .second = 2 }; const q = p.swapped(); std.debug.print("{d} {d}\n", .{ q.first, q.second });}Output:
2 1The struct { ... } inside Pair has no name of its own, so @This() is the only way to refer to it from its methods. Don’t worry about comptime T: type yet; it’s how Zig does generics, covered in Zig Generic Data Structures. The reference entry for @This shows the same idea with a list type.
pub and who can see what
Section titled “pub and who can see what”You’ve been writing pub fn. pub makes a declaration visible outside the file it’s in. Inside the same file, you can call a method with or without pub. So for a small single-file program, leaving it off seems to make no difference, until some other code needs to call your function.
The standard library is that “other code”. When you print with {f}, it’s std that calls your format method, and std lives in other files:
const std = @import("std");
const Temperature = struct { celsius: f64,
fn format(self: Temperature, writer: *std.Io.Writer) std.Io.Writer.Error!void { try writer.print("{d:.1} C", .{self.celsius}); }};
pub fn main() void { const t: Temperature = .{ .celsius = 21.5 }; std.debug.print("{f}\n", .{t});}lib/std/Io/Writer.zig:1181:32: error: 'format' is not marked 'pub' 'f' => return value.format(w), ~~~~~^~~~~~~main.zig:6:5: note: declared here fn format(self: Temperature, writer: *std.Io.Writer) std.Io.Writer.Error!void { ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Add pub in front of fn format and it prints 21.5 C. A good habit: mark methods pub when they’re part of how people use your type, and leave helpers private. Fields don’t take pub; they’re always visible.
The init and deinit habit
Section titled “The init and deinit habit”Zig has no constructors or destructors. Instead there’s a strong convention, used all over the standard library:
initis a function that returns a ready-to-use value. It’s not special, just a name everyone uses.deinitcleans up: it frees memory or closes things the value owns. You call it yourself, usually withdeferright after creating the value.
A nice detail: when Zig knows the result type, you can call init without the type name, as .init(...). The same works for constants inside the struct:
const std = @import("std");
const Point = struct { x: i32, y: i32,
pub const origin: Point = .{ .x = 0, .y = 0 };
pub fn init(x: i32, y: i32) Point { return .{ .x = x, .y = y }; }};
pub fn main() void { const a: Point = .init(3, 4); const b: Point = .origin; std.debug.print("a = ({d}, {d}), b = ({d}, {d})\n", .{ a.x, a.y, b.x, b.y });}Output:
a = (3, 4), b = (0, 0).init(3, 4) means Point.init(3, 4), and .origin means Point.origin, because the type annotation says the result is a Point. Zig calls these decl literals. You’ll meet them constantly: var list: std.ArrayList(i32) = .empty; is exactly this.
deinit matters once a struct owns memory. Here’s a shelf of book titles stored in a growable list (an ArrayList, from Zig ArrayList). The list needs an allocator to get memory, and it has to give it back at the end:
const std = @import("std");
const Shelf = struct { books: std.ArrayList([]const u8) = .empty,
pub fn add(self: *Shelf, gpa: std.mem.Allocator, title: []const u8) !void { try self.books.append(gpa, title); }
pub fn deinit(self: *Shelf, gpa: std.mem.Allocator) void { self.books.deinit(gpa); }};
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
var shelf: Shelf = .{}; defer shelf.deinit(gpa);
try shelf.add(gpa, "Dune"); try shelf.add(gpa, "Emma"); for (shelf.books.items) |title| { std.debug.print("- {s}\n", .{title}); }}Output:
- Dune- EmmaThe shape is what matters here: create the value, defer its deinit on the next line, then use it. Forget the deinit, and init.gpa reports a leak when the program ends. The !void and try are there because asking for memory can fail; that’s Zig Try & Catch. Allocators get a full lesson in Zig Allocators, and more ways to shape init (options structs, builders) are in Zig Design Patterns.
What Zig doesn’t have
Section titled “What Zig doesn’t have”If you come from an object-oriented language, it helps to know what’s missing on purpose:
- No inheritance. One struct can’t extend another. If you want to reuse one, put it in a field.
- No hidden
this. A method gets the value only through its first parameter. - No overloading. Two functions in a struct can’t share a name with different parameters.
- No automatic cleanup. Nothing runs when a value goes away.
deinitplusdeferis how you do it.
It’s less to learn, and when you read a call like shelf.add(gpa, "Dune"), there’s exactly one function it can be.
Practice
Section titled “Practice”1. A rectangle with two methods
Section titled “1. A rectangle with two methods”Give a Rect struct (width and height, both u32) two methods: area and perimeter. Print both for a 3 by 4 rectangle.
Hint: both methods only read the rectangle, so self: Rect is right. The perimeter is 2 * (width + height).
Show solution
const std = @import("std");
const Rect = struct { width: u32, height: u32,
pub fn area(self: Rect) u32 { return self.width * self.height; }
pub fn perimeter(self: Rect) u32 { return 2 * (self.width + self.height); }};
pub fn main() void { const r: Rect = .{ .width = 3, .height = 4 }; std.debug.print("area {d}, perimeter {d}\n", .{ r.area(), r.perimeter() });}Output:
area 12, perimeter 14Neither method changes the rectangle, so r can stay const.
2. A bank account
Section titled “2. A bank account”Make an Account with a balance: u64 and two methods: deposit(amount) adds money, and withdraw(amount) takes money out only if there’s enough, returning true if it worked and false if not. Deposit 100, then try to withdraw 30 and 500.
Hint: both methods change the balance, so they need self: *Account, and the account must be a var.
Show solution
const std = @import("std");
const Account = struct { balance: u64 = 0,
pub fn deposit(self: *Account, amount: u64) void { self.balance += amount; }
pub fn withdraw(self: *Account, amount: u64) bool { if (amount > self.balance) return false; self.balance -= amount; return true; }};
pub fn main() void { var acc: Account = .{}; acc.deposit(100); std.debug.print("withdraw 30: {}\n", .{acc.withdraw(30)}); std.debug.print("withdraw 500: {}\n", .{acc.withdraw(500)}); std.debug.print("balance: {d}\n", .{acc.balance});}Output:
withdraw 30: truewithdraw 500: falsebalance: 70Checking amount > self.balance first matters: balance is unsigned, so subtracting too much would overflow and crash in a Debug build.
3. Fix the level-up
Section titled “3. Fix the level-up”This program should print level 2, but it doesn’t build. Fix it with as few changes as you can.
const std = @import("std");
const Player = struct { level: u32 = 1,
pub fn levelUp(self: Player) void { self.level += 1; }};
pub fn main() void { const p: Player = .{}; p.levelUp(); std.debug.print("level {d}\n", .{p.level});}Hint: two things need to change: the method has to get a pointer, and the player has to be changeable.
Show solution
const std = @import("std");
const Player = struct { level: u32 = 1,
pub fn levelUp(self: *Player) void { self.level += 1; }};
pub fn main() void { var p: Player = .{}; p.levelUp(); std.debug.print("level {d}\n", .{p.level});}Output:
level 2self: *Player lets the method change the caller’s player instead of a copy, and var p allows it to be changed. The call p.levelUp() stays the same.
- Functions declared inside a struct live in its namespace: call them as
Type.func(). - When the first parameter is the struct, you can call it as a method:
r.area()isRect.area(r). - Use
self: Tto read andself: *Tto change. Zig takes&for you at the call, but the value must be avar. @This()is the struct you’re inside; you need it for structs with no name, like generic ones.pubmakes a declaration visible to other files, includingstd, which is whyformatmust bepub.- The
init/deinitconvention replaces constructors and destructors; calldeinitwithdefer. - With a known result type,
.init(...)and.originwork without the type name (decl literals).
Next up: Zig Enums, for values that can only be one of a fixed list of names.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: struct: methods, namespaced declarations and the
Vec3.dotexample. - Zig language reference: @This: the builtin, with a generic list example.
- Zig 0.17.0 release notes: includes the
@hasDeclchange that makespubmatter more. - Zig standard library source: array_list.zig: a real struct with
init-style constants,deinitand manyself: *Selfmethods.