24 ms·
Rust should have untagged unions. Obviously, ones that allow pointer abuse would be restricted to code marked unsafe. Note that a union of two pointer-containi
by milspec 11y ago
Rust should have untagged unions. Obviously, ones that allow pointer abuse would be restricted to code marked unsafe.
Note that a union of two pointer-containing structs is safe as long as the pointers line up, having the same type and offset in each struct.
- jroesch 11y agoDo you have a compelling use case? I can't imagine a use for untagged unions in Rust that isn't subsumed by other features in the language.
- mbrubeck 11y agoThe most common use case would be interop with C libraries that use untagged unions. This is a significant hassle when writing C bindings in Rust today.
- Jweb_Guru 11y agoI can think of many, mostly revolving around cases where the tag is not stored inline with the structure in question. Where space efficiency is important this is quite common. C interoperability is obviously another important use case (the current solution of passing around [u8] arrays is pretty atrocious).
- comex 11y agoThey've been proposed: https://github.com/rust-lang/rfcs/pull/724 https://github.com/rust-lang/rfcs/pull/724 If you really need them, you can implement them in a library by declaring a suitably sized byte array and having methods that return casted pointers to it. This would be illegal in C due to strict aliasing, but IIRC Rust does not have a strict aliasing rule (because almost all pointers being the equivalent of 'restrict' drastically reduces the benefit). There are issues with size_of not being a constant expression and such (at least in stable), but those are definitely going to be fixed.