How can i pass a read only reference around which is guaranteed to live as long as the program lives?

I have a config struct which is initialized as soon as main starts running and I pass a reference of it to all other places.
When I pass it to my endpoints I get the compiler error saying the lifetime 'static is required to be specified.
Since the struct is coming from env vars at runtime I cant declare the pointers of it as static the compiler says it doesn't live long enough. How do I explain rust that the reference will for sure be there always and its okay to share the immutable references of it across threads ?

Box it and leak. Or use the lazy_static crate to initialize and store it globally.

The life of main is not static because there's still a little bit of execution after main returns, all the way until the exit syscall actually kills the remaining threads. That's a small window where those other threads could still access their references, so we don't want anything to be dangling.

There's nothing special about this treatment -- rather it's that main is not special at all, and gets the same lifetime treatment as any other function. Note, you can even call it again from elsewhere if you like.

1 Like

i ended up using Arc

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.