I've got a struct that is so large it would be unwieldy if not separated into several sub-structs across multiple files in a dedicated module. However, then each sub-struct no longer has access to the fields/methods of the main struct.
My first thought was to just put an
Option reference back to the top-level struct into each struct that needed it. While that would seem to compile, I'm realizing it doesn't correctly deal with the "one mutable or any immutable" references limit.
Fortunately, only one of the sub-structs needs to be mutable, though many of the immutable sub-structs depend on the variable values from the mutable one. So I could perhaps divide the top level into mutable and immutable halves and have the mutable portion contain a reference to just the immutable half for access to its values and methods. That seems like it might be viable, but would be a larger departure from the original architecture.
Alternately, and requiring less overall refactoring, I could put the mutable sub-struct in a
Mutex and leave the top level struct immutable. I think in either case I might need to have the mutable portion emit an
Arced immutable snapshot of it's data for use with the other immutable sub-structs' methods. These would probably also require a mutable builder for setup which would implement
Into the immutable/
Mutex version for actually running a simulation.
However, before I go for any major refactoring, I was wondering if anyone knew of any design patterns for dealing with this concept? I've mocked up a very generic version of the alternate (less-refactored) version in the playground as a start, but it's not feeling like the best option... I'd like to avoid heap allocation of what will just be medium-sized collections of
f64 values (so taking advantage of
Arc/RwLock/Mutex if possible).
Any thoughts would be greatly appreciated!