Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement long-lived variables/state in a library?

Tags:

rust

I understand that the preferred way to implement something like a global/instance/module variable in Rust is to create said variable in main() or other common entry point and then pass it down to whoever needs it. It also seems possible to use a lazy_static for an immutable variable, or it can be combined with a mutex to implement a mutable one.

In my case, I am using Rust to create a .so with bindings to Python and I need to have a large amount of mutable state stored within the Rust library (in response to many different function calls invoked by the Python application).

What is the preferred way to store that state?

Is it only via the mutable lazy_static approach since I have no main() (or more generally, any function which does not terminate between function calls from Python), or is there another way to do it?

like image 523
Ginty Avatar asked Oct 24 '25 05:10

Ginty


1 Answers

Bundle it

In general, and absent other requirements, the answer is to bundle your state in some object and hand it over to the client. A popular name is Context.

Then, the client should have to pass the object around in each function call that requires it:

  • Either by defining the functionality as methods on the object.
  • Or by requiring the object as parameter of the functions/methods.

This gives full control to the client.

The client may end up creating a global for it, or may actually appreciate the flexibility of being able to juggle multiple instances.

Note: There is no need to provide any access to the inner state of the object; all the client needs is a handle (ref-counted, in Python) to control the lifetime and decide when to use which handle. In C, this would be a void*.


Exceptions

There are cases, such as a cache, where the functionality is not impacted, only the performance.

In this case, while the flexibility could be appreciated, it may be more of a burden than anything. A global, or thread-local, would then make sense.

like image 137
Matthieu M. Avatar answered Oct 26 '25 03:10

Matthieu M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!