Zig Struct Methods
A struct method is a function defined inside a struct that works on that struct's value. Calling a method with a dot lets a value act on its own data.
Read a field through a method
The get method reads the count field through self. Printing its return value shows the stored count.
const std = @import("std");
const Counter = struct {
count: i32,
pub fn get(self: Counter) i32 {
return self.count;
}
};
pub fn main() !void {
const out = std.io.getStdOut().writer();
const c = Counter{ .count = 7 };
try out.print("{d}\n", .{c.get()});
}
Change the original with a pointer self
The inc method takes self as a pointer to Counter. Two calls raise the stored count by two.
const std = @import("std");
const Counter = struct {
count: i32,
pub fn inc(self: *Counter) void {
self.count += 1;
}
};
pub fn main() !void {
const out = std.io.getStdOut().writer();
var c = Counter{ .count = 10 };
c.inc();
c.inc();
try out.print("{d}\n", .{c.count});
}
Return values computed from fields
One method returns the area of a rectangle. Another method returns its perimeter.
const std = @import("std");
const Rect = struct {
width: i32,
height: i32,
pub fn area(self: Rect) i32 {
return self.width * self.height;
}
pub fn perimeter(self: Rect) i32 {
return 2 * (self.width + self.height);
}
};
pub fn main() !void {
const out = std.io.getStdOut().writer();
const r = Rect{ .width = 4, .height = 6 };
try out.print("{d} {d}\n", .{ r.area(), r.perimeter() });
}
Example
const std = @import("std");
const Player = struct {
score: i32,
pub fn add(self: *Player, points: i32) void {
self.score += points;
}
};
pub fn main() !void {
const out = std.io.getStdOut().writer();
var p = Player{ .score = 5 };
p.add(10);
p.add(3);
try out.print("{d}\n", .{p.score});
}
Key points
- Method: A method is a function declared inside a struct.
- Self: The first parameter is named self and it carries the struct value.
- Read: A method with self: Counter receives a copy of the value to read.
- Mutate: A method with self: *Counter receives a pointer, which lets it change the original value.
- Call: Write c.inc() to call the inc method on a value named c.
- Return: A method can return a value computed from its fields.
In this example, the Player starts with a score of 5. The add method takes a pointer self and a points value, so its two calls change the original score to 18.
Note
In Zig, methods use the same dot syntax as field access.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which self type lets a method change the original struct value?