Enum to variable length string

Hi,
I am new to Zig and I don’t fully understand the difference between slices and strings. I want a CardValue enum that can return the value as a string for messages.

pub const CardValue = enum(u8) {
    two = 2,
    three = 3,
    four = 4,
    five = 5,
    six = 6,
    seven = 7,
    eight = 8,
    nine = 9,
    ten = 10,
    jack = 11,
    queen = 12,
    king = 13,
    ace = 14,

    pub fn toString(self: CardValue) ??? {
        return switch (self) {
            .two => "two",
            ... and so on
       };
    }
};

I come from memory managed languages like Java and Python. What would be a good idea here? Should I allocate these words on the heap and return a C-style pointer? Or should I just return an u8 array with the length of the longest word?

1 Like

just use @tagName(self). You can just return a []const u8 as that is the type of a string literal. It will be in the constant data section of the binary, no allocation required.

1 Like

Oh that’s neat, I missed that builtin! Thanks! :slight_smile: