Union
A union is a type where all members share the same memory location. The size of a union is the size of its largest member. Writing to one member overwrites the data of all other members.
Value :: union {
as_int: s64;
as_float: float64;
as_bytes: [8] u8;
}
In this example, as_int, as_float, and as_bytes all occupy the same 8 bytes of memory. Assigning a value to as_int and then reading as_bytes lets you inspect the raw byte representation of that integer.
v: Value;
v.as_int = 42;
print("first byte is %\n", v.as_bytes[0]);
Unions are useful when a piece of data can be interpreted in multiple ways, or when you need to reinterpret the bit pattern of one type as another. They are also used in combination with an enum tag to build tagged unions, where the enum tracks which member is currently valid.
Token_Kind :: enum {
INTEGER;
FLOAT;
IDENTIFIER;
}
Token_Value :: union {
as_int: s64;
as_float: float64;
as_string: string;
}
Token :: struct {
kind: Token_Kind;
value: Token_Value;
}