4 ms·
I was wondering myself why you needed a union type. Is it because JS has dynamic types ? var x = 5; x = "John Doe";
by toong 13y ago
I was wondering myself why you needed a union type.
Is it because JS has dynamic types ?
var x = 5;
x = "John Doe";
- jessedhillon 13y agoThe alternative is a data structure which has N-1 empty, yet allocated, slots (N is the number of possible types.) instead you can have one field indicating the type of the variable and then your code can switch which field it accedes based off that indication. Total size is one int plus size of largest type represented.
- 1631- 13y agoYou could potentially also have an interface that defined methods for all the basic types `interface { AsString() (string, error), etc. }` and then each basic type implements this interface and returns an error if it can't/shouldn't be represented as the requested type. A type-switch could give you the same info you get from the tag and you don't pay for type-assertions
- astrodust 13y agoIt allows you to create a single, compact structure that can then be utilized in a number of ways without having to re-cast it, replace it, or otherwise reallocate it. For example, you can have a union between a 64-bit pointer and a 32-bit type identifier plus 32-bit value. This means you can store 32-bit integers in the same space as a pointer.
- cdcarter 13y agoThe question is what about a JS interpreter makes this necessary.
- ek 13y agoAs I answered above to another commenter with a similar question, JavaScript is a dynamically typed language and representing dynamic values in a statically typed language requires a bit of thinking, and unions are a common way of doing this.
- ek 13y agoYes. JavaScript has dynamic types, and representing these in a statically typed language requires some finagling.