TLDR; This is more a discussion than a plea for help. I am asking for feedback on how to organize three objects in relationship while keeping the borrowing rules under control. I have an idea, but it may not be best. I wanted to run it past more experiences rustaceans
Assumption: An immutable Token
cannot have a field that references a mutable State
.
After about 100 hours of really working in rust (not just doing the tutorials, but working on an actual project), I feel like I'm starting to think in rust and appreciate the borrow checker. I have an architecture decision to make and I don't just want to do what I did in Java.
So, I have a Token
that is deserialized from a json manifest. None of its data ever needs to be mutated by anyone.
That Token
can also have Storage
, which is a growable byte heap. That data will be mutated by the user.
That Token
also has a State
which will not be mutated, but will be replaces as needed.
Each Token
has exactly one Storage
and State
by relationship. Storage and State have no direct relationship.
The Token
is kept in a TokenManager
and references are handed out as needed. I wanted to keep the Token
immutable, so I didn't have to worry about the borrow checker as much. However, in order to keep the Token
immutable, I can't simply attach the Storage
and State
, that would mean mutating Token
to replace State
, and making Token
mutable to have a field that is mutable (Storage
).
So, my idea is to give each Token
a unique id, and have a StateManager
and a StorageManager
to hold all states and storage. Then, on the Token
object, add methods that simply call the StateManager
and StorageManager
.
There are some issues with this approach:
- I will either have clone the state and storage whenever it is returned, or fight the borrow checker.
- I can't have a reference to either the
StateManager
orStorageManager
on theToken
, or it would have to be mutable, which I don't want. So, I'll have to workout some static non-sense.
Specific Questions:
- Is this a case for interior mutability?
- How could I use static methods on the State and Storage Managers so the
Token
doesn't need a direct reference? - Is there an entirely different approach I should consider?
Solved. Here is my working concept: Architecture Suggestions for Idiomatic Rust - #7 by electricjones