Sometimes, it is useful to have a structure with multiple representations. This may be achieved with properties, but there is also a more direct way of doing it: using unions and anonymous structs. We'll create a Color
structure with both RGBA and array representations.
To create a structure with two views into the same data, we need to execute the following steps:
Write a struct to contain your type.
Add a union without a name to hold the alternative representations.
In the union, add the views. Be sure they match up in size and binary layout. For our
Colorstruct
, we'll want it to be represented by an array ofubytes
with each byte also having a name.For the names, write a nameless
struct
with each named member.When using the structure, use the names directly.
To implement the preceding steps, we will have to execute the following code:
struct Color { union { ubyte[4] rgba; struct { ubyte r; ...