Unions

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.


Defining a Union

union DataUnion {
    a: int;
    b: float64;
}

func main() {
    #un = DataUnion;
    un.b = 3.14;
}

Union Initialization

Unions can be initialized using a Union Initializer, specifying which field to set at creation:

#un: DataUnion = DataUnion { a: 10 };
  • Only one field should be initialized at a time.
  • Initialization sets the union's memory to store the specified field's value.