`const Self = @This();` in nested structs

What if I write generic like this

const std = @import("std");

fn StupidGeneric(comptime T: type) type {
    const U = struct {
        const This = @This();
        a: T,
        b: T,

        fn addThem(thing: This) T {
            return thing.a + thing.b;
        }
    };
    return U;
}

pub fn main() void {
    const StupidFloat = StupidGeneric(f32);
    const sf = StupidFloat{.a = 1.2, .b= 3.4};
    std.debug.print("{}\n", .{sf.addThem()});
}

?
This joky example is very similar to yours - we have some struct defined inside a function and therefore we have to use @This(), otherwise we will get use of undeclared identifier 'U'.

Anonymity is not mandatory as it turned out, see my previous comment.

My original “problem” (which is not actually a problem at all) was that I mistakenly used Self = @This() for two structures, outer and inner. As we saw Zig does not allow this, so the solution for that initial “problem” is:

  • either do not use @This() aliasing, use original struct names
  • or use different aliases for outer and inner structs (Outer=@This(), Inner=@This())
2 Likes