How to get the active field type of a union value and check if it has a specified declaraiton?

For a specified example, how will the method hasAtomicDecl be implemented?

const std = @import("std");

const T = union(enum) {
	x: struct {
		const isAtomic = void;
	},
	y: struct {
	},
	
	fn hasAtomicDecl(self: T) bool {
		...
	}
};

const fields = std.meta.fields(A);

pub fn main() !void {
	var a: T = .{.x = .{}};
	var b: T = .{.y = .{}};
	std.debug.print("{}, {}\n", .{a.hasAtomicDecl(), b.hasAtomicDecl()});
}

You can put the following in hasAtomicDecl:

return switch (self) {
    inline else => |s| @hasDecl(@TypeOf(s), "isAtomic"),
};
5 Likes

Many thanks! It is so clean. Zig is cool.

3 Likes