-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Allow extern tagged unions #1072
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
What's a use case of having a tag name, you can access it in Zig through the struct regardless and there is a standard naming procedure for the produced header? Is there ever a need for just the 'tag' and not the whole union. |
In the C headers generated, a tag name is required for the union to be useful in C code. |
Yes, but I meant couldn't we just have a standard name like |
Sure, we can do that. It was just an idea to avoid field name collisions completely while allowing the tag name to be something not ugly. Keep in mind, this feature is for C using a Zig lib. The users of your lib would appreciate |
Fair enough, I can see that being much more pleasant 👍 |
Ideas for how to set the tag name for extern unions are welcome :) I remember @andrewrk mentioning that all parameters to keywords should be |
I'd like to reconsider this issue in light of #1922 |
extern struct {
tag: enum(u8){
a,b,c,
},
data: extern union(.tag){
a: A,
b: B,
c: C,
},
} |
Just to be clear about about the problem, here is a comparison the status quo vs what is being proposed: status quopub const S = extern struct {
tag: enum(i32) {
A,
B,
},
data: extern union {
A: u16,
B: u8,
},
};
const s: S = ...
switch (s.tag) {
.A => {
// use s.data.A, which could be undefined behavior
},
.B => {
// use s.data.B, which could be undefined behavior
},
} proposedpub const S = extern struct {
tag: enum(i32) {
A,
B,
},
data: extern union(.tag) { // the union(.tag) part is subject to change
A: u16,
B: u8,
},
};
const s: S = ...
switch (s.data) {
.A => |a| {
// a is u16
},
.B => |b| {
// b is u8
},
} |
Sometimes you need to provide a tagged union through your C api. Currently, the best way to do this is to declare an extern struct with a tag, and a union member:
But is there really any reason that extern tagged unions shouldn't work? We could make this:
Equivalent to this header:
The only problem I see here is that the "tag" has to be given some name in the C header. If this is a problem, we could introduce a syntax like this:
This would give the tag a name, and make it accessible from both Zig and C.
The text was updated successfully, but these errors were encountered: