How to do a static initializer?

I wonder how to do a static initializer with Rust, like what you would do with Java?

My scenario is that I want to fill a HashMap with a couple 'insert' calls like:

static {
     hashmap.insert(foo1, bar1);
     hashmap.insert(foo2, bar2);
     hashmap.insert(foo3, bar3);
     ... etc ...

If I use a lazy loading mechanism, say, with OnceCell etc (implementing a singleton using a mutex guard for example) , unfortunately in my situation I have no place to trigger this lazy loading. So the question is: can I do a dlopen, when the above code in a dynamic module gets loaded, the code also gets executed?

Are you, by any change, at some place using that HashMap you’d like to fill? That place where you use the HashMap might be a candidate for a “place to trigger this lazy loading”.

Or perhaps you’re talking about a case of collecting such map entries from different crates into a single map. There’s been discussions about this scenario somewhere, somewhat recently, I’ll look up where that was.

Edit: This was the thread I remembered. It mentions current approaches using existing crates such as ctor that hook into the linker somehow or something like that IIRC, and also discusses ideas for more proper solutions that Rust could offer in the future for different use-cases.


For something like once_cell::sync::Lazy, you don't actually need a place to trigger the initialization because your static variable will be initialised the first time it gets used.

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.