Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Rust not have unions?

Tags:

rust

I can think of many places where unions in C help are useful and they save memory. As Rust is a system programming language, why doesn't it support unions?

like image 458
unnamed_addr Avatar asked Mar 25 '15 06:03

unnamed_addr


People also ask

Does Rust have discriminated unions?

Enums in Rust are discriminated unions that can save one of the multiple variants. The enum discriminator identifies the current interpretation of the discriminated union.

What are unions used for in Rust?

The key property of unions is that all fields of a union share common storage. As a result, writes to one field of a union can overwrite its other fields, and size of a union is determined by the size of its largest field. Union field types are restricted to the following subset of types: Copy types.

What is a union Rust?

The Rust equivalent of a C-style union. A union looks like a struct in terms of declaration, but all of its fields exist in the same memory, superimposed over one another.


1 Answers

Unions were added to the language in (RFC 1444), and they are stable as of Rust 1.19.0. They require usage of unsafe blocks.

Raw unions are not memory-safe (as there is no way for the compiler to guarantee that you always read the correct type (that is, the most recently written type) from the union). One of the goals of Rust is to create a low-level language with memory safety; since unions are not compatible with that goal, they were not included in Rust 1.0.

Instead, Rust has enums, which provide most of the advantages of unions in exchange for a small memory usage, but which are memory safe since the enumeration value always keeps track of which particular type it contains.

like image 192
Mankarse Avatar answered Nov 18 '22 22:11

Mankarse