Hard coding 2000+ constants of the same type

This question is a bit weird. If it’s not clear what I’m asking, please point out the confusion (so I can improve the question) rather than guessing the question.

Here is the problem:

  1. I have “pub struct MeshData { … }”

  2. I have 2000+ objects of type “MeshData” – they have names apple_red, apple_green, apple_rotten, …, orange_big, orange_tangerine, orange_mandarin, …, chair_wooden, chair_plastic, chair_aeron, …, car_truck, car_tesla, car_f1, …

  3. This list of objects is static, determined at COMPILE TIME, and does NOT CHANGE during runtime.

  4. I want to hard code this list of items into a *.rs file – so that rustc can, statically, at compile time, notify me any missing object.

=====

Here are the solutions I have considered:

sol1_dont_do_this:

This “solution” is not acceptable as I really want compile time checking / warning of any non-existent object.

sol2_use_const

Here ,we can either have a single module, mesh::car_…, mesh::orange_… ,
or submodules mesh::car::: … mesh::orange::…, …

This is the best solution I have so far.

What I don’t like about this is that IntelliJ wants me to name consts using all caps, i.e.

mesh::car::TRUCK , mesh::car::TESLA, …

=====

Any other suggestions?

The replacement of ::car:: with the ::car:: was not intentional.

1 Like

This question is not “how do I use emoji’s as module/variable names in rust” :slight_smile:

2 Likes

So disable that lint with #![allow(non_upper_case_globals)] at the top of the module.

Also, you might want to use static instead of const. consts are effectively copy+pasted everywhere you use them, statics are actual storage in the compiled binary.

1 Like

Thanks, was unaware of ‘const’ vs ‘static const’.

Not static const, just static.

1 Like

chair_wooden, chair_plastic, chair_aeron,

I’m not sure if it’s helpful in your case, but Rust idiomatic way would be to have:

enum Item {
    Orange(OrangeKind),
    Chair(ChairKind),
}

enum ChairKind {
    Wooden, Plastic, Aeron,
}

and when you match against them, they are checked at compile time.

Mapping these to external constants is trickier. You’d probably end up with a huge match block or two. There are also crates that add custom metadata to enums, like strum.

2 Likes

The static approach worked fine. Despite the naming convention, there (at least so far) hasn’t been a situation where:

  1. I have some object
  2. I know it is a Chair
  3. I don’t know which type of chair it is