#Why @sizeOf(tag) field in unions must be equal to alignment?

1 messages · Page 1 of 1 (latest)

limpid turtle
#

The following code doesn't pass the final assert:

pub const TestStruct = union(SmallEnum) {
    one: struct { a: u8, b: u32 },
    two: struct { b: u32 },
};
pub const SmallEnum = enum(u8) { one, two };

comptime {
    std.debug.assert(@sizeOf(TestStruct) == 8);
}

Why is @sizeOf(TestStruct) == 12 when in both union cases there is more than enough space to fit in the SmallEnum tag of u8 size into 8 bytes? Is this a compiler bug?

mortal gull
#

no, the compiler does not eagerly pack the tag into padding

#

a tagged union is essentially

struct {
  tag: E
  data: untagged union {}
}
limpid turtle
#

So there is no way to make a union of size 8 where total bitsize of one of its members is 5 bytes?

mortal gull
#

bitsize is irrelevant here, the byte size of one's struct is 8 bytes

limpid turtle
#

Feels then like there should be a way to put inside one struct something like { place_tag_here, a: u8, b:u32} :D. There is no underlaying limitation to prevent this from working. It is simply a Zig language limitation, right?

mortal gull
#

it's a missed optimization that may be implemented in the future

#

just like every other optimization that the compiler could and does not yet apply