Constructing union values is very similar to constructing struct values:
type_name { [field_initializer] }
The main difference is that union constructors require either exactly one field initializer, or none. Specifying initialization values for more than one field doesn’t make sense in the case of unions.
Suppose we have the following union type:
type Packet = union { byte b : b > 0; int k; };
If we try to construct a Packet
with an invalid b
, we
get a constraint error:
(poke) Packet {b = 0} unhandled constraint violation exception
The reason why k
is not chosen is because we specified b
in the union constructor: we explicitly as for a Packet
of that
kind, but the data we provide doesn’t accommodate to that. If we
wanted another kind of value, we could of course specify an initial
value for k
instead:
(poke) Packet {k = 10} Packet { k=10 }
If no field initializer is specified in an union constructor then each alternative is tried assuming all fields have default values, which in the case of integral types is a zero:
(poke) Packet {} Packet { k=0 }
Therefore the alternative b
is considered invalid (it has to be
bigger than 0) and k
is chosen instead.