#Possible to get the address of tagged union prior to initialization?

1 messages · Page 1 of 1 (latest)

trail portal
#

I am heap allocating a tagged union, but one of the fields of this union requires an address to "self", so to speak.

const myUnion = try gpa.create(MyUnion);
myUnion.* = .{
    .known_tag = .{
        .some_field = .{ .ptr = &myUnion.known_tag, .vtable = ... },
    }
};

This currently panics with "cannot access union field 'known_tag' when '...' is active"

I get what Zig is trying to do here, but also, it would be annoying to assign some_field = undefined and then update it on the next line.

cold umbra
#

try @unionInit

trail portal
#

Why would that help in this case?

cold umbra
#

ah

#

thats strange

#

are you sure you assigned everything?

#

inside known_tag?

#

if you dont it wont switch

uneven siren
#
const myUnion = try gpa.create(MyUnion);
myUnion.* = .{.known_tag = undefined};
myUnion.* = .{
    .known_tag = .{
        .some_field = .{ .ptr = &myUnion.known_tag, .vtable = ... },
    }
};
#

@trail portal

#

that way you set it to that tag before getting the ptr

trail portal
#

Yup, I realise this works. It's just a bit annoying 🤷‍♂️

uneven siren
#

yes

#

it sucks a little

#

why do you need the known_tag ptr in some_field to begin with

#

are you sure you can't use @fieldParentPtr()

#

that would be simpler', not have this issue and make your struct smaller

robust rapids
#

Wait, wouldnt:

const myUnion = try gpa.create(MyUnion);
myUnion.* = .{
    .known_tag = .{
        .some_field = .{ .ptr = myUnion, .vtable = ... },
    }
};

work fine?