4 ms·
The right solution was to make union safe with an opt-in way to make it unsafe IMO.
by sirwhinesalot 3y ago
The right solution was to make union safe with an opt-in way to make it unsafe IMO.
- steveklabnik 3y agoIn concrete terms, what would that look like?
- metaltyphoon 3y agoSyntax wise Zig does it with union(enum). Union and Enums are both concepts directly related to C and can be used separately too.
- mattstir 3y agoThe thing is that accessing an untagged union's data is just inherently unsafe. Say you made a union with a `u8` field and a `bool` field. If you had an instance of it and set its value to `5`, that's just not a valid `bool`. Hence the requirement of `unsafe`; you need to tell the compiler that you _know_ it's a valid value at the point you're accessing it.
- sirwhinesalot 3y agoThen make them tagged, that's what rust enums are, tagged unions, except they're called enums instead of unions.
- mattstir 3y agoI mean... yeah, that's exactly why Rust has tagged unions as well... both are useful in the right contexts, but tagged unions are easier to work with in general. That doesn't mean that (untagged) unions should be safe to work with though, because they can't be.