Skip to content

Instantly share code, notes, and snippets.

@peterhellberg
Created August 22, 2025 12:26
Show Gist options
  • Save peterhellberg/f797e09d8f4154624eb10da0781be55e to your computer and use it in GitHub Desktop.
Save peterhellberg/f797e09d8f4154624eb10da0781be55e to your computer and use it in GitHub Desktop.
Usage of @fieldParentPtr instead of the now removed usingnamespace
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));
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment