#tagged union "subtype"

1 messages · Page 1 of 1 (latest)

thorn granite
#

Say I have a tagged union, all entries having the same type :

pub const Tags = enum {
    a,
    b,
    c,
};
pub const Data = union(Tags) {
    a: u32,
    b: u32,
    c: u32,
};

Is there a way to define a type that corresponds to a Data with a given tag?
For example, I would like to be able to express that a function always returns a Data with the active tag a. What would be the type of this return type?

thorn granite
#

ok 😢
I will look for another approach

little inlet
#

Oh that was linked already, missed that. Sorry

thorn granite
#

yes it was already linked, but I fail to see how to use this..

little inlet
#

Well instead of a u32 you'll have a unique integer type. This way you can express which kind of u32 is returned.

#

However you would have to return that type instead of the union type though. If that doesn't work with your logic and you must return the union then it won't help.

#

Maybe have 3 functions, each returns a named unique integer type, or aliased integer type. Then a wrapper function with a comptime switch that would return the union.

#

But I would say this is an unnecessary abstraction