Skip to content

Instantly share code, notes, and snippets.

@gruebite
Last active April 26, 2021 22:04
Show Gist options
  • Save gruebite/51cc7bf72348b91394aa9397c72822e2 to your computer and use it in GitHub Desktop.
Save gruebite/51cc7bf72348b91394aa9397c72822e2 to your computer and use it in GitHub Desktop.
Zig dynamic dispatch with @fieldParentPtr
const print = @import("std").debug.print;
const Animal = struct {
const Self = @This();
speakFn: fn(*const Animal) void,
pub fn speak(self: *const Self) void {
self.speakFn(self);
}
};
const Dog = struct {
const Self = @This();
animal: Animal,
call: []const u8,
fn init() Self {
return .{
.animal = .{
.speakFn = speak,
},
.call = "bark!",
};
}
fn speak(animal: *const Animal) void {
const self = @fieldParentPtr(Dog, "animal", animal);
print("{}\n", .{self.call});
}
};
const Cat = struct {
const Self = @This();
animal: Animal,
call: []const u8,
fn init() Self {
return .{
.animal = .{
.speakFn = speak,
},
.call = "meow!",
};
}
fn speak(animal: *const Animal) void {
const self = @fieldParentPtr(Cat, "animal", animal);
print("{}\n", .{self.call});
}
};
fn doStuff(animal: *const Animal) void {
animal.speak();
}
pub fn main() void {
const dog = Dog.init();
doStuff(&dog.animal);
const cat = Cat.init();
doStuff(&cat.animal);
}
@tau-dev
Copy link

tau-dev commented Apr 26, 2021

Your cat has an identity crisis.

@gruebite
Copy link
Author

gruebite commented Apr 26, 2021

Nice, haha. The perils of manual vtables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment