Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

Why does Rust not have unions?

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?

question from:https://stackoverflow.com/questions/29248665/why-does-rust-not-have-unions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...