Last active
April 26, 2021 22:04
-
-
Save gruebite/51cc7bf72348b91394aa9397c72822e2 to your computer and use it in GitHub Desktop.
Zig dynamic dispatch with @fieldParentPtr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
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
Your cat has an identity crisis.