Using Tagged Unions member function

I have this tagged union:

pub const Lex = union(enum) {
    EOF,
    IDENT: []const u8,
    LPAREN,
    RPAREN,

    pub fn toString(allocator: std.mem.Allocator, self: *Lex) ![]const u8 {
        return switch (self.*) {
            .LPAREN => try std.fmt.allocPrint(allocator, "L_PAREN ( null", .{}),
            // .IDENT => |val| try std.fmt.allocPrint(allocator, "IDENT {s}", .{val}),
            .RPAREN => try std.fmt.allocPrint(allocator, "L_RAREN ) null", .{}),
            .EOF => try std.fmt.allocPrint(allocator, "EOF null", .{}),
            else => try std.fmt.allocPrint(allocator, "UNKNOWN_LEX", .{}),
        };
    }
};

but when I’m trying to call it getting an error:

        const tokens: ArrayList(Lex) = try token.tokenize(std.heap.page_allocator, file_contents);
        for (tokens.items) |tkn| {
            try stdout.print("{s}\n", .{tkn.toString(std.heap.page_allocator)});
        }
        defer tokens.deinit();

Error:

src/main.zig:28:44: error: no field or member function named 'toString' in 'token.Lex'
            try stdout.print("{s}\n", .{tkn.toString(std.heap.page_allocator)});
                                        ~~~^~~~~~~~~
src/token.zig:5:17: note: union declared here
pub const Lex = union(enum) {
                ^~~~~
src/token.zig:11:9: note: 'toString' is not a member function
    pub fn toString(allocator: std.mem.Allocator, self: *Lex) ![]const u8 {

The error note tells you the problem:

‘toString’ is not a member function

Member functions must have self as the first parameter.

3 Likes

I didn’t understand why it was not member, so being inside the scope doesn’t help :)))

By definition, a member function requires that first “self” parameter. Simply being in the scope of the struct / union / enum does not make it one.

@ziggon you found an interesting “accidential feature”/bug in this forum (discourse), by capitalizing Zig when specifying your code block language, you select the zig parsing without the custom highlighting css that only works with the .lang-zig css-class. (But not with .lang-Zig)

Which is why your code blocks fallback to the default discord highlighting instead of the custom zig-highlighting (that is based on the colors of the Zig language reference).

I am a bit surprised that the language doesn’t get lowercased automatically.
I think it may be better if we all use the lowercase zig variant (so we don’t have multiple different highlighting styles for the same language in the forum), or actually you don’t have to specify the language at all, because zig is the default language.

1 Like