Unions with fields of generic types

i have two different generic type functions G(T: type, ...) type and H(T: type, ...)… in my use-case, i have a comptime create function that will return an instance of either G(T) or H(T)…‘’

the parameters to my create function are sufficient to invoke G() and H() internally…

for the result type of create, i presumably return a union with would contain “tags” named g and h… since create is presumably parameterized by T, i can consequently declare the types of g and h as G(T, ...) and H(T, ...)

since i originally wanted to return an INSTANCE of G(T) or H(T), would my create function being returning an instance of my generic union type with either g or h assigned in the initializer???

i’m still having a little trouble imagining what this would look like… not sure if this is “common idiom” in zig…

This skeleton may be what you’re looking for. It’s a common pattern in std when you have a dynamic return type like this.

fn Create(comptime T: type) type {
    if (is_g) return G(T);
    else return H(T);

pub fn create(comptime T: type) Create(T) {
    return .{ ... };

Here’s a translation of the provided code snippet:

pub fn rstPanel(comptime T: type , vsrc: *T , vdst : *PANEL) void {...

pub: This indicates that the function is public, meaning it can be accessed from outside its module.
fn: This keyword is used to define a function.

rstPanel: This is the name of the function.
comptime T: type: This declares a compile-time parameter T of type type. In this context, it means that T must be resolved at compile time.

vsrc: *T: This declares a parameter vsrc of type *T, which is a pointer to a value of type T. link T(comptime)

vdst: *PANEL: This declares a parameter vdst of type *PANEL, which is a pointer to a PANEL type object. To UPDATE

void: This indicates that the function doesn’t return a value.

{…}: This is the body of the function, where you would write the actual implementation.

as there was no code I offered you an example, sorry

seems simple… one issue i found when experimenting is that ZLS support in VSCode would often fail to figure out return type…

in my use-case, i’ll be the author of these generic types – and i want my client to have a “good experience” vis-a-vis VSCode… ensuring that the types are not “unknown” and that a list of type members pops-up when the user enters a “.” is very important…

perhaps for reason i thought a more explicit union(enum) type might help in VSCode…

i actually have a “working solution today” not unlike your snippet… it just show well in VSCode…

1 Like

i will say designing around the current functionality of ZLS is maybe a local maximum… what ZLS (or whatever tooling Zig comes up with) is able to give hints about is going to be a moving target for a long time.


can you post your solution