r/rust • u/Koltaia30 • 2d ago
🙋 seeking help & advice How can I protect a shared object from mutation ?
I have a config struct which I want to pass around to be read by several object. I want it to be written to by some objects like the save loader and debug stuff. What is the general way to achieve this in rust?
PS: It's a single threaded application
7
Upvotes
48
u/dvogel 2d ago
Create two types. Each holds an
Rc<RefCell<MyConfigStruct>>. One type exposes a read-only APi. The other a read-write API.14
u/Cyan14 2d ago
For single thread, use Rc<RefCell<T>>. For multi thread, use Arc<RwLock<T>>
For read only, you can pass reference (&), Box<T>, Rc<T> or Arc<T>
Box, Rc, Arc are smart pointers, heap allocated. RefCell and RwLock / Mutex allows mutability even when you don't have a &mut reference, by using a runtime check.
5
u/SplittyDev 2d ago
Simply give it to the read-only parts of the app as an immutable reference (&Config) instead of a mutable one (&mut Config).
2
u/NullOfSpace 2d ago
To clarify, you have a shared object that you want to be able to write to from some references but not from others? Do you need to write to it after some locations already have immutable references, or is it enough to set up all of the mutable stuff first, then make it permanently immutable?
1
u/edfloreshz 2d ago
For a single-threaded application, the usual solution is Rc<RefCell<T>>
1
u/mina86ng 2d ago edited 2d ago
Something like:
(Obviously not tested, might need some tweaks).
Rcisn’t necessary, but depending on how patient you are with adding lifetime everywhere you may use it to simplify some code.If you want to make it multithreaded, replace
RefCellwithRwLockorMutex.3
u/nick42d 2d ago
I feel like you could structure this differently. For example, of storing references inside your objects, are you able to give them immutable references only when they need it (e.g, to a function that responds to events or draws a ui frame?). Then you can mutate wherever the config is owned at any other time.
2
u/TrickAge2423 2d ago
What about left_right?
1
u/coolmint859 2d ago edited 2d ago
Honestly I would consider the data flow of the config struct. It may be simpler and more robust to think of it as a pipeline, from creation to last usage.
If the config is meant to be read and written from indefinitely, consider inverting the usage so that some central owner (or the config itself) borrows the types that mutate the state of the config, and have the owner request the new data from them, rather than the writers accessing the config directly. It's much safer that way. (You can then wrap the inner values in Cell or RefCell so that you can borrow self immutably)
This also allows the readers to only need an Rc<T> or a simple & reference, since mutation is centralized.
0
u/ern0plus4 2d ago
Separate read-only data from read-write first.
0
u/AugustusLego 2d ago
Consider using an actor model. Sending a request over a broadcast channel, which contains a oneshot channel for the response