Sharing state between functions

In writing various pieces of Rust if often come across places in my code where I would like several functions to share some common piece of infrastructure without having to re-initialise it. Things like tokio runtimes or hubcaps instances. In terms of program design I could share these instances by passing them in to each function, but that means that the caller has to care about something that I consider an implementation detail of the function. I'm wondering what patterns people use to deal with this issue in Rust? In Scala I would use a class to allow this sort of sharing that would be initiliased at application startup, but obviously an equivalent concept doesn't really exist within Rust. I have looked at the lazy_static crate however for many of my shared values this approach does not seem to work.

Can you explain why lazy_static doesn't work for you?

Well for Tokio Runtimes for example they need to be mutable, which doesn't seem to work with lazy_static

(worth mentioning that my app is single threaded, so I am not concerned about sharing mutable state)

You can mutable stuff with lazy_static but you need interior mutability, like Mutex or RwLock. If you are 200% sure you'll never use threads and you need the maximum performance possible, you should be able to get away with something lighter weight like RefCell.

1 Like

Note that lazy_static requires Send + Sync, if you are running a single threaded app, then you can use std::thread_local! { .. } which works similarly to lazy_static, but gives you a thread local value. This means that you can use Cell/RefCell for unsyncronized shared mutability.


Great, thanks for your replies!

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