2 ms·
Is a union type (at least in Haskell/Rust) structured like a union in C, where alternative types of values (e..g. int, float, char) occupy the same bytes, just
by vram22 11y ago
Is a union type (at least in Haskell/Rust) structured like a union in C, where alternative types of values (e..g. int, float, char) occupy the same bytes, just not at the same time? Or is separate space allocated for the different types of values? Asking because, if a function returns a union type, with one type within it representing an integer (which can have any value), and if the function also wants to return an error condition, then no valid integer value can be used to indicate the error, because all integer values are valid return values from the function. In this case I would think that a union type should have separate space allocated for the integer value and the error-signalling value. (Something like what golang does with its return values?)
- steveklabnik 11y agoThere are two major forms of sum type implementations that I'm aware of: tagged and untagged. What you're describing is a tagged union, for exactly the reason you state: there's an extra field for a discriminant which lets you choose the tag. Untagged unions are C's unions, where there's no discriminant, and you just have to know which type is valid at a given time. Rust supports tagged unions, but can also optimize them to untagged in certain circumstances. We will probably add some kind of untagged union as well, mostly for FFI, but they're very unsafe, for the above reasons.
- vram22 11y agoGot it, thanks. Interesting about Rust's design goals and tradeoffs.
- 0cachecoherency 11y agoSimilarly, Pony's union (ie sum) type implementation always optimises to untagged, but required "boxing" raw machine-words when they're in a union type.