Design Question: Shared State

This is not a question about shared state as it relates to concurrency. It’s a much simpler question than that.

Rust seems to discourage keeping any data content "global", so that multiple methods can refer to it and even change it. But let's say I’m programming code to play a board game. What if I’m getting very tired of passing the current board -- with piece positions -- around from method to method.

What would be a good design choice to enable a board to be kept off to the side somewhere, where other code could just drop by and make a move (i.e., change the state), instead of passing the same data content from place to place?

This may sound highly specific, but assuming there's a solution, it's a general design concept that could be useful in many situations. Thanks for any suggestions.

What are these methods on? If there is a self parameter, can you store the board in that type?

1 Like

You could store the data in several structs by using reference counted pointers and allow mutable access in a synchronized way, RefCell if it is single threaded or RWLock for a multithreaded program.

The key problem is to make the following design goal concurrency-safe, including thread-safe:

Because the Rust language is designed to let the rustc compiler aggressively optimize code, all non-local interactions need either to be proven correct at compile-time, or employ run-time locking and guard primitives (including atomic) to ensure run-time memory and thread safety.

Thank you everyone for your suggestions. I'm considering each one and implementing a solution now. I appreciate the help!

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