0

I'm rolling my own entity component system.

Is there a way of mapping struct types to integers?

I could implement a toInt() for each struct, but it feels inelegant to execute code to get a number which could be known at compile-time.

I'm rather not take care of the numbering myself (it doesn't need to be stable) and just "register" a handful of struct types with a "numberer" at compile time.

I'm looking for an API along the lines of:

struct Foo {
    ...
}

struct Bar {
    ...
}

struct Baz {
    ...
}

struct Quux {
    ...
}

register!(Foo, Bar, Baz);

numberOf!(Foo) == 0;
numberOf!(Bar) == 1;
numberOf!(Baz) == 2;
numberOf!(Quux) == failure of some kind;

Is there a way of doing this?

fadedbee
  • 42,671
  • 44
  • 178
  • 308
  • It looks like your question might be answered by the answers of [How can I statically register structures at compile time?](https://stackoverflow.com/q/32678845/155423); [Generating unique IDs for types at compile time](https://stackoverflow.com/q/25372477/155423); [Does Rust track unique object ids and can we print them?](https://stackoverflow.com/q/30157258/155423) . If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jan 17 '20 at 14:07
  • "I could implement a toInt() for each struct, but it feels inelegant to execute code to get a number which could be known at compile-time." why do you suppose it's will not be optimized ? maybe use a const function. And why not use an enum or dyn trait ? You are coding in Rust why don't you use the feature available ? What the point ? – Stargateur Jan 17 '20 at 14:09
  • See specifically [this answer](https://stackoverflow.com/a/57419729/155423) – Shepmaster Jan 17 '20 at 14:10
  • If you want a macro that implements a `to_int` or defines a `const ID`, for each struct. Then check out this question instead: https://stackoverflow.com/questions/31195529/escaping-commas-in-macro-output – vallentin Jan 17 '20 at 14:17
  • @Shepmaster Thanks for the links, https://stackoverflow.com/a/48906500/129805 was what I was looking for. – fadedbee Jan 17 '20 at 14:17

0 Answers0