Comment by sph
3 days ago
Tagged enums != any type (i.e. runtime casting)
Tagged enums are everywhere. I am writing a micro kernel in C and how I wish I had tagged enums instead of writing the same boilerplate of
enum foo_type {
FOO_POINTER,
FOO_INT,
FOO_FLOAT,
};
struct foo {
enum foo_type type;
union {
void *val_pointer;
int val_int;
float val_float;
};
};
> ...runtime casting...
...what else is a select on a tagged union than 'runtime casting' though. You have a single 'sum type' which you don't know what concrete type it actually is at runtime until you look at the tag and 'cast' to the concrete type associated with the tag. The fact that some languages have syntax sugar for the selection doesn't make the runtime overhead magically disappear.
Not sure why you call it runtime overhead. That’s core logic, nothing fancy, to have a pointer to a number of possible types. That’s what `void *` is, and sometimes you want a little logic to restrict the space of possibilities to a few different choices.
Not having syntactic sugar for this ultra-common use case doesn’t make it disappear. It just makes it more tedious.
There are many implementations and names, and what I refer to runtime casting/any type, which is unnecessary for low-level programming, is the one that uses types and reflection at runtime to be 100% sure you are casting to the correct type. Like Go’s pattern (syntax might be a bit off):
This is overkill for low-level programming and has much higher overhead (i.e. having to store type info in the binary, fat pointers, etc.) than tagged unions, which are the bread and butter of computing.