reference
reference copied to clipboard
union for an unsafe form of enum
I've noticed you said a feedback regarding readability of this guide is welcome some time ago, so I'll try to leave some as I'm following along. I haven't used Github issues before (everyone has to start somewhere I guess), so if I'm doing it wrong please be so kind as to give me some suggestions.
While reading the chapter about union types, it was not clear to me what the following paragraph meant:
Unions are kind of like enums, but they are “untagged”. Enums have a “tag” that stores which variant is the correct one at runtime; unions don't have this tag. Since we can interpret the data held in the union using the wrong variant and Rust can’t check this for us, that means reading a union’s field is unsafe:
...and then the code shows usage that closely resembles one of Rust's enums, so it wasn't clear what made it different and why "unsafe" keyword was needed.
I've figured out some more knowledge on how unions work in C was needed, and I have found the following Quora answer to give me a better understanding about union's memory representation and what exactly makes it unsafe, in particular the following quote:
In a C program, a "union" type is given a memory layout that "overlaps" the layout of A and B in memory. For example, if you have a union of a 16-bit int and a 64-bit pointer to an integer, the compiler will use 64 bits (which is max(16,64) to represent the union type. The problem that then arises, is that you have no way to know whether the value in the location is a 16-bit integer or a 64-bit pointer.
I think providing a similar explanation would help readers who haven't used union types in C.
The following Medium article sorted out the remaining confusions for me, so a link for an additional reading with a simple explanation like that could also be desirable.
Also, how does pattern matching on unions work if the type ("tag") isn't stored for them? How does Rust know which branch to choose?
Transferred to the reference, as potential feedback for improving the union chapter. (This issue was originally on the edition-guide, which no longer discusses unions, but I think the feedback is still useful.)