const Counter = struct {
v: u8,
fn increment(self: *Counter) void {
self.v += 1;
}
};
test Counter {
var c: Counter = .{ .v = 0 };
(&c).increment();
try std.testing.expectEqual(1, c.v);
c.increment();
try std.testing.expectEqual(2, c.v);
}
A key feature of zig is that when self is a struct and a method requires self to be a pointer, self.method can be called directly, rather than (&self).method.
This approach may be convenient for a newly initialized struct. However, it can lead to misuse when copying content. It can cause users to forget that the API they are copying is based on pointers, not entire structs. Users should obtain a pointer to the copied object, but instead directly copy the struct, causing subsequent use to deviate from their intended purpose without notice.
For example, std.Io.Writer is an example. After directly copying an interface, users can directly call interface.method(), forgetting that the copied object is not a pointer, and that the structure it uses requires a pointer, potentially leading to misuse.
var interface = writer.interface;
interface.print("hello, world", .{});
interface.flush();
If users were forced to use this here, they would likely reflect and realize their mistake:
var interface = writer.interface;
(&interface).print("hello, world", .{});
(&interface).flush();
I originally thought that a key reason for this feature was generic functions. Sometimes generic functions are passed values, and sometimes pointers. This feature bridges the gap between pointers and values, allowing their methods to be executed consistently.
But after some reflection, I feel this isnât entirely tenable. If the API executed within a generic function requires some parameters to be pointers and some to be values, then this distinction should be reflected in the generic functionâs parameters. Generic function parameters shouldnât be passed values ââand then converted to pointers internally for execution, which could easily lead to errors.
Is there something Iâm missing where strong support for this feature would make coding extremely difficult if it didnât exist?