Comptime Enum Value Declarations

I’ll wait for other answers to roll in, but this post from @AndrewCodeDev coincidentally sort of answered my question! Here is a decent way to avoid code duplication when you have many methods that might be rather long:

const std = @import("std");

const comptime_option = true;

const SomeEnumImpl = struct {
    pub fn someMethod(self: SomeEnum) u32 {
        return @intFromEnum(self);
    }
    pub fn otherMethod(self: SomeEnum) u32 {
        return @intFromEnum(self) * 2;
    }
};

const SomeEnum = if (comptime_option) enum(u32) {
    a = 0,
    b,
    c,
    d,

    pub const someMethod = SomeEnumImpl.someMethod;
    pub const otherMethod = SomeEnumImpl.otherMethod;
} else enum(u32) {
    // Different ints for each value!
    a = 0,
    c,
    d,
    b,
    // More values!
    x,
    z,

    pub const someMethod = SomeEnumImpl.someMethod;
    pub const otherMethod = SomeEnumImpl.otherMethod;
};

pub fn main() void {
    std.debug.print("Works: {d}\n", .{SomeEnum.b.someMethod()});
    std.debug.print("Compile Error!: {d}\n", .{SomeEnum.x.someMethod()});
}

You duplicate code by defining the public const members for each method, but is a lot more compact than duplicating the entire method code.

2 Likes