Skip to content

Instantly share code, notes, and snippets.

@lukebayes
Last active May 30, 2021 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukebayes/11ab2b194ad25572f64b2e6788142d92 to your computer and use it in GitHub Desktop.
Save lukebayes/11ab2b194ad25572f64b2e6788142d92 to your computer and use it in GitHub Desktop.
Zig Polymorphism / Delegation
const std = @import("std");
const print = std.debug.print;
pub fn Abstract(comptime T: type, comptime R: type) type {
return struct {
const Self = @This();
impl: *T = T{},
pub fn exec(self: *const Self) R {
print("Abstract.exec\n", .{});
return self.impl.exec();
}
};
}
pub const ConcreteOneItem = struct {
name: []const u8 = "one",
};
pub const ConcreteOne = struct {
pub fn exec(self: *ConcreteOne) ConcreteOneItem {
print("ConcreteOne.exec\n", .{});
return ConcreteOneItem{};
}
};
pub const ConcreteTwoItem = struct {
name: []const u8 = "two",
};
pub const ConcreteTwo = struct {
pub fn exec(self: *ConcreteTwo) ConcreteTwoItem {
print("ConcreteTwo.exec\n", .{});
return ConcreteTwoItem{};
}
};
test "Create Abstract" {
print("\n\n", .{});
const one = Abstract(ConcreteOne, ConcreteOneItem){};
const oneItem = one.exec();
print(">> one name: {s}\n", .{oneItem.name});
const two = Abstract(ConcreteTwo, ConcreteTwoItem){};
const twoItem = two.exec();
print(">> two name: {s}\n", .{twoItem.name});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment