Global structs with immutable content

I to define a few encodings, say that maps String <-> u8. The list of such mappings is closed and short. Mappings may be const, user will not be allowed to modify them.

There also be plenty of objects (structs); each of them requires it's own mapping - one of these above. How to implement this in rust? I want these mappings to be cheap in terms of memory.

In C++ I'd implement a singleton MappingManager with enum keys; each object would contain the key to its mapping.

Rust provides no built-in way to initialize a static object at program startup. You can make a static MaybeUninit global and initialize that at startup explicitly from main (with a wrapper accessor that gets rid of the MaybeUninit).

You can also use lazy_static or static_init, the difference is that lazy_static is ... lazy (somewhat like a magic static in c++) and static_init just knows how to hook into the platform support for global constructors and destructors. I personally prefer static_init most of the time.

as for the structs you can have a trait with like "get_mapping() -> &'static Mapping" or something similar.

You could also define each mapping as a unit-less enum, and use something like the strum crate to allow constructing one from the name. You might need to be careful to specify that things are constructed from an array or map rather than nested if statements.

1 Like

Thanks for the answer!

I don't actually need the mappings to be static; I can even load them from a file. What I really want is to avoid copying them for each of my objects. I expect to have ~10 mappings and even ~10^6 objects that are using them.

So I like the idea with an enum that contains a mapping as its own data. Will the data be copied when I'm copying an enum? Or maybe it behaves like a pointer to the same object?

A given mapping must contain a HashMap, if that counts.

Take a look at the phf crate.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.