Created
August 22, 2025 12:26
-
-
Save peterhellberg/f797e09d8f4154624eb10da0781be55e to your computer and use it in GitHub Desktop.
Revisions
-
peterhellberg created this gist
Aug 22, 2025 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,46 @@ const std = @import("std"); pub fn main() !void { var a = Counter(u32){}; var b = Counter(i32){ .value = 41 }; a.count.increment(); b.count.increment(); std.debug.print("a: {}\tb: {}\n", .{ a.value, b.value }); a.count.reset(); a.count.decrement(); b.count.reset(); b.count.decrement(); std.debug.print("a: {}\tb: {}\n", .{ a.value, b.value }); } pub fn Counter(comptime T: type) type { return struct { value: T = 0, count: Mixin(@This()) = .{}, }; } pub fn Mixin(comptime T: type) type { return struct { pub fn increment(m: *@This()) void { m.parent().value +|= 1; } pub fn decrement(m: *@This()) void { m.parent().value -|= 1; } pub fn reset(m: *@This()) void { m.parent().value = 0; } fn parent(m: *@This()) *T { return @alignCast(@fieldParentPtr("count", m)); } }; }