union Examples

Let’s look at a few examples of unions.

We'll cover the following...

Communication protocol

In some protocols like TCP/IP, the meanings of certain parts of a protocol packet depend on a specific value inside the same packet. Usually, it is a field in the header of the packet that determines the meanings of successive bytes. Unions can be used for representing such protocol packets.

The following design represents a protocol packet that has two kinds:

Press + to interact
struct Host {
// ...
}
struct ProtocolA {
// ...
}
struct ProtocolB {
// ...
}
enum ProtocolType { A, B }
struct NetworkPacket {
Host source;
Host destination;
ProtocolType type;
union {
ProtocolA aParts;
ProtocolB bParts;
}
ubyte[] payload;
}
void main() {}

The struct ...