Bitwise » Forums » Compound literals for unions are clumsy
yanok
2 posts
#14744 Compound literals for unions are clumsy
2 months, 3 weeks ago Edited by yanok on March 28, 2018, 11:05 a.m.

It's really strange that we need to provide all the fields to create the union. Isn't it the whole point behind unions that only one of the fields is actually needed?
pervognsen
Per Vognsen
46 posts
1 project
#14745 Compound literals for unions are clumsy
2 months, 3 weeks ago Edited by Per Vognsen on March 28, 2018, 12:19 p.m.

You don't need to provide all the fields. Fewer will do, with implied zero padding, as in C. But yes, since right now I haven't implemented named fields for compound literals, union compound literals are not terribly useful. It's not a reflection of a language issue, just the fact that named fields for compound literals haven't been implemented. I'll do it right now...
pervognsen
Per Vognsen
46 posts
1 project
#14746 Compound literals for unions are clumsy
2 months, 3 weeks ago Edited by Per Vognsen on March 28, 2018, 2:18 p.m.

OK, just checked it in, though it's only received some light testing.

https://github.com/pervognsen/bit...211f0181e16397e3205e9782f2acfaf20

You can now do stuff like this and it properly type checks:

1
2
3
4
union IntOrPtr { i: int; p: int*; }
var u1 = IntOrPtr{i = 42}
var u2 = IntOrPtr{p = cast(int*, 42)}
var a: int[256] = {1, 2, ['a'] = 3}


Thanks for the prod. :)
yanok
2 posts
#14747 Compound literals for unions are clumsy
2 months, 3 weeks ago

Cool! Thanks!