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:
A color union is a good example:
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
What is the difference between a union and a discriminated union?
What is the profit of using unions?
What could be an usage screnario of using a discriminated union?
Last updated