0

This is a problem I’ve run into in several languages when creating libraries.

Say I’m writing an event system. I might want to have several event keys, and it would be most efficient to store them as integers. My first thought would be to create an enum of event keys, which makes sense if I have access to the definition. Also suppose that there’s some internal built-in enumerations that I need to make things work.

If I’m a consumer of this event system library, I won’t have access to the enum definition and therefore won’t be able to add my own entries.

The way I’ve solved it in the past is with a struct that has contains a single integer and a private constructor called by some manager object that automatically increments the discriminator value. This works fine, but it’s not ideal.

A problem with this implementation is that the number is not necessarily known at compile-time, and if I wanted to create an array with a length equal to the number of variants, I couldn’t.

I can imagine that rust would have some ability to create something like this in a constant context, but I’m not sure how. Is there some way to do this with macros and/or constant functions? Afaik const fn can’t have state, but if it did, I could have it handle the auto-incrementing

Jam
  • 476
  • 3
  • 9
  • If you want the available events to be changeable, why not use some sort of dynamic storage (e.g. a set or map with initial values consisting of the predefined ones)? – John Bayko May 27 '23 at 04:54

0 Answers0