3 ms·
> And tagged unions have to be at least the size of the largest variant, sometimes plus the tag (right? Or is that just true in rust?). That's correct. If you
by kristoff_it 4y ago
> And tagged unions have to be at least the size of the largest variant, sometimes plus the tag (right? Or is that just true in rust?).
That's correct. If you have wildly different sizes, you can create a union of pointers. It will require you to manage the memory for the concrete implementation separately, but this way you will not waste space.
const Foo = union(enum) {
dog: *Dog,
cat: *Cat,
// ...
};
> With rust traits, to use the example in the post, when you define a function that takes an "Animal", it will basically generate a version of the function that takes a Cat, and one that takes a Dog, and double checks that Cat and Dog both have `talk` implementations. So the tradeoff is you get static dispatch with no wasted space in the data representation, at a cost of more code generation.
Yes, that post is specifically about the need for dynamic dispatch, in Zig you can get monomorphization like so:
fn makeAnimalTalk(animal: anytype) void {
// optionally use some metaprogramming to validate `animal`
// and produce a custom compile error when the trait is not
// fulfilled.
animal.talk(); // will work on any type that can be used like that
}