There is sample code on how to create "interface" like functionality using @fieldParentPtr in the following video. Its a little out of date and doesn't compile:
https://youtu.be/AHc4x1uXBQE?t=682
UPDATE: I've added the fixes inline to the code below. Thanks!
const Widget = struct {
drawFn: *const fn (*@This(), *usize) void,
fn draw(self: *@This(), ctx: *usize) void {
self.drawFn(self, ctx);
}
};
const TextArea = struct {
widget: Widget,
rect: [4]usize,
text: []const u8,
fn init(rect: [4]usize, text: []const u8) @This() {
return .{ .widget = .{ .drawFn = @This().draw }, .rect = rect, .text = text };
}
fn draw(widget: *Widget, ctx: *usize) void {
const self: *@This() = @fieldParentPtr("widget", widget);
ctx.* +%= self.rect[0] +% self.rect[1] +% self.rect[2] +% self.rect[3];
}
};
pub fn main() void {
var text_area = TextArea.init(.{ 0, 0, 10, 10 }, "Initial text...");
var widget = &text_area.widget;
var sum: usize = 0;
widget.draw(&sum);
}
I am wondering if someone might know what the following errors mean, and how to resolve them:
tmp % zig run widget.zig
widget.zig:16:31: error: expected pointer type, found 'widget.TextArea'
const self: @This() = @fieldParentPtr("widget", widget);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
From Zig SHOWTIME #17
Subscribe to the Zig SHOWTIME Newsletter!
https://zig.show
0:00 Title
0:30 Talk
31:56 Interview