Unions

Unions

An union can be used to hold a value with different types. Unions can be used to avoid casting.

The syntactic structure of an union:

<memory_offset> ::= <int_number>
<union_value> ::= "let" <name> "=" <memory_offset> ";"
<union_declaration> ::= <modifier>? "union" <name> "{" <union_value>* "}"

A color union is a good example:


public union Color {
    let mut R: u8 = 0;
    let mut G: u8 = 1;
    let mut B: u8 = 2;
    let mut A: u8 = 3;

    let value: u32 = 0;
}

The value field can be used to convert all color values (RGBA) to a u32 integer without casting. An union allocates memory for the most sized variable type. In this example the whole union will allocate 4 bytes because the biggest type used in the union is u32.

Discriminated Unions

A discrimated union (DU) is a typed union. It can be used to create a hierarchical type structure easily. And Du's are generating a default constructor and a ToString method. You will see that discrimated unions are saving a lot of lines of code.

The structure of DU's:

For example we will create a simple DU for an abstract syntax tree:

The normal equivalent class structure would be:

Exercices

  1. What is the difference between a union and a discriminated union?

  2. What is the profit of using unions?

  3. What could be an usage screnario of using a discriminated union?

Last updated