#[solved] Avoid duplicated enum syntax in tagged union. Possible?

1 messages · Page 1 of 1 (latest)

rich ibex
#
pub const Pragma = union(enum) {
  pure, Inline, Noreturn, readonly,

  const Id = enum {
    pure, Inline, Noreturn, readonly,

    const Map = std.StaticStringMap(Pragma.Id);
    pub const map = Map.initComptime(.{
      // Keywords
      .{ "inline",     Pragma.Id.Inline   },
      .{ "readonly",   Pragma.Id.readonly },
    });
  };
}
```Is there a way to avoid this Enum to be duplicated, and still have access to each tag as a struct as usual?
low phoenix
#

do you mean like this? you still need to define the fields twice though

const Id = enum {pure, Inline, Noreturn, readonly};

const Pragma = union(Id) { pure, Inline, Noreturn, readonly };
rich ibex
#

no, I mean accessing each item as a struct

#

thats essentially still duplicating the enum tags

#

you just got it out of the union, but yours is the exact same I wrote 🤔

#

can I use the tagged union itself for the values of the StaticStringMap, and still store only the tag part??
I think that would solve the tags being duplicate, but dont know if its legal syntax

barren briar
#

like this?

pub const Pragma = union(enum) {
  pure, Inline, Noreturn, readonly,

  const Id = std.meta.Tag(Pragma);
  const Map = std.StaticStringMap(Pragma.Id);
  pub const map = Map.initComptime(.{
    // Keywords
    .{ "inline",     Pragma.Id.Inline   },
    .{ "readonly",   Pragma.Id.readonly },
  });
}
rich ibex
#

epic! yeah, exactly @barren briar ! tytyty 🙏

#

oh wait, but that creates a slice, not an enum 🤔

#

is that going to work without an enum type?

barren briar
#

huh? std.meta.Tag returns the tag type of Pragma, which should be equivalent to enum { pure, Inline, Noreturn, readonly }

rich ibex
#

ohhhh. i used tags, not Tag

barren briar
#

oh ive never even used that one lol

#

but yea theyre very different

rich ibex
#

yeah, lol. Tag seems to work though. tyty!

barren briar
#

sweet zeroLike