Union

Unions are like enums that don't store the currently used variant. Accessing a union field is inherently unsafe because of this. Unions were added to Rust for better compatibility with C, but are useful in pure Rust as well.

A union has several fields that share the same memory. Therefore, when instantiating a union, only one of its fields is specified. It is possible to access a different field of a union than the one that was previously set, which re-interprets the bytes similarly to.

Like struct fields, union fields are private by default and can have visibility modifers.

Example
Note that the above is sound:  has the same size as. Furthermore, the union ensures that both values have the same alignment, which isn't the case for.

Fields of different sizes
Unions can contain fields of different sizes. In that case, the size of the union equals the size of its biggest field, including padding. One use case is the type: This union allows manually initializing a value, such as an array, without overhead.

Limitations
Currently, unions can only contain types that implement. Note that  uses the   nightly feature to support non-  values.