As packed union does not support attatching enum, so there is not way to detect which field of a packed union is active?

For example, the following code doesn’t compile:

// const U = packed union (enum) { // error: packed union does not support enum tag type
const U = packed union {
    x: bool,
    y: u8,
};

pub fn main() void {
	const u: U = .{.x = true};
	switch (u) { // error: switch on union with no attached enum
		.x => {},
		.y => {},
	}
}

Does this mean which field of a packed union is active must be known at coding time?

packed union is used only inside a packed struct, you can use an enum field in the packed struct to determine which union field is active.

2 Likes

Packed union is a variant of a union which supports a well defined memory layout. The enum tag feature is not compatible because it has not been implemented to provide a well defined memory layout.

To know what union field is active you need memory available to store what field is active. (An additional hidden u3 or something like that).

In a regular union, this can be accomplished by the compiler putting the tag in between fields or adding an additional hidden field.

Packed unions have no padding (what you write for the fields is what is in memory), so the compiler doesn’t have any memory to work with without violating the expectations of the programer.

Maybe there could be special sytax or something in the future to allow you to give the compiler memory to work with for the tag, but this is currently not implemented.

Yes, or you need to be careful and have another field somewhere and keep it updated with what union field is active.

1 Like

Thank both for the explanations and the (same?) solution.

Now, I think I’m clear on the issue. It looks packed union is more like C union.