A Union in Cyrus is a composite data type similar to C-style unions. It allows multiple fields to share the same memory location, so only one of its fields can hold a valid value at any given time. Unlike structs, assigning a value to one field will overwrite the memory for other fields.
⚠️ Warning: Unions in Cyrus are not memory-safe. Reading a field that was not most recently written is undefined behavior, just like in C. Use unions only when you explicitly need memory-efficient, low-level data representations.
✅ Safe Alternative: If you want a memory-safe way to store different types of values, use an enum, which enforces at compile time which variant is active.
union DataUnion {
a: int;
b: float64;
}
func main() {
#un = DataUnion;
un.b = 3.14;
}
Unions can be initialized using a Union Initializer, specifying which field to set at creation:
#un: DataUnion = DataUnion { a: 10 };