Last active
May 30, 2021 01:11
-
-
Save lukebayes/11ab2b194ad25572f64b2e6788142d92 to your computer and use it in GitHub Desktop.
Zig Polymorphism / Delegation
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 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