Search⌘ K

union Examples

Explore how to implement unions and discriminated unions in D to handle data with varying types safely and efficiently. Understand how these constructs help represent protocol packets, provide type safety, and enable versatile collections through examples and D language features.

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:

D
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 ...