#Enum coercion to Superset

1 messages · Page 1 of 1 (latest)

fresh arch
#

I have a tagged union like this:

pub const Instruction = union(enum) {
  group1: enum { a, b, c },
  group2: enum { d, e, f },
  group3: enum { A, B, C, D }, 
  pub const Real = blk: {
    // superset enum of group1 and group2, in the same order i.e. enum { a, b, c, d, e, f }
  };
  pub fn parse_instruction(reader: *std.Io.Reader) !Real {
    // this only returns Real because every items from group3 actually map to items in
    // group1 and group2
    ...
  }
};

Right now, parse_instruction loops over std.meta.fieldTypes(Instruction) and uses std.meta.stringToEnum to parse and validate a potential value. However, I want to map this to a tag in Real ( which may require some intermediate computation ).

Thinking about it, I could probably do something like @field(Real,@tagName(parsed_tag)), but this feels a little clunky--I am planning to make the Real just a portion of the return struct, and it will also contain some additional information.

Is there a way to coerce these enums that I parse into a superset enum with a tag of the same name?

jovial arrow
#

i think @field(Real,@tagName(parsed_tag)) is the way to go.
there used to be std.enums.nameCast which basically did same thing

olive dome
#

there is no way to coerce them, zig does not have the concept of super/sub sets.
(well error sets kindof do, but thats not relevant)

you will need to make some kind of api, there are a lot of ways to do this, just do what makes the most sense to you.