carbon-lang
carbon-lang copied to clipboard
Equivalent of C++ (nameless) union with nameless structs
(C++)
template<typename T> struct vec4 { T x, y, z, w; };
struct color {
union {
vec4<float> data{ 0, 0, 0, 0};
struct { float r, b, g, a };
};
};
I understand that choice types are tagged unions, but there is no example or mention about how someone would implement the above code in Carbon. Also there is no mention of nameless unions. I would imagine it could be somewhat like below.
(Carbon)
class Vec4(template T:! Type) { var x: T; var y: T; var z: T; var w: T; };
class Color {
choice {
Data: Vec4(f32) = (.x = 0, .y = 0, .z = 0, .w = 0), // I hope this is correct
struct { var R: f32; var G: f32; var B: f32; var A: f32; };
};
};
While something like this isn't essential, the following points are why this should be added if it is not already;
- Cleaner code
- More readable code
- Interoperability with C++
- Straight forward to implement (As to write and understand)
Side note: Are you able to declare vars like var x, y, z, w: f32?
Carbon will very likely eventually have support for un-tagged unions, but there isn't a design yet. I proposed one in #139, but dropped it because there were some tricky design questions to resolve, and I figured out a way to get it off the critical path for tagged unions, which was my main priority at the time. If you or someone else wants to propose a design for un-tagged unions, that might be a good starting point, although some aspects of it are pretty outdated by now.
Side note: Are you able to declare vars like
var x, y, z, w: f32?
No, although you can do var (x: f32, y: f32, z: f32, w: f32) = .... A name binding always consists of a single name, then a :, then a type expression.
if you or someone else wants to propose a design for un-tagged unions
Thanks, I'll probably do that when I have time
We triage inactive PRs and issues in order to make it easier to find active work. If this issue should remain active or becomes active again, please comment or remove the inactive label. The long term label can also be added for issues which are expected to take time.
This issue is labeled inactive because the last activity was over 90 days ago.