How to make a comparison method in an enum

The Zig guide has an error on their website, but I really want to be able to use a feature like this, this code doesn’t work:

const expect = @import("std").testing.expect;

const Suit = enum {
    clubs,
    spades,
    diamonds,
    hearts,
    pub fn isClubs(self: Suit) bool {
        return self == Suit.clubs;
    }
};

test "enum method" {
    try expect(Suit.spades.isClubs() == Suit.isClubs(.spades));
}

The method inside the enum says that ‘Suit’ isn’t declared yet. Any solutions?

Works for me on Zig v0.13.0 with zig test. How are you running it?

2 Likes

This issue should only arise when you’re defining the enum in an imperative scope, ie a function, a test, or a comptime block.

fn function(...) ... {
    // we're in an "imperative scope" 
    const MyEnun = enum {
        _ = MyEnum; // <- this is an error
    };
}

// at root-level we're in a "declarative scope"
const YourEnum = enum {
     _ = YourEnum; // <- this is ok because even though it's not fully defined yet, it's declared and in a declarative scope
};

I don’t have my computer now but the snippet you provided shouldn’t have any problem unless I missed something. If it does, could share the output of the compiler?

Edit: if you’re in a declaring it in an imperative scope, use @This() instead of the name of your type. This function directly references the nearest container within which it’s called.

3 Likes

Ah I see, I was running it in main. Thanks for the help!