I have an enum which represents the state of my application, and each state carries some data that is relevant for this state. Say for example:
enum State {
FirstState, // this has no data
SecondState(String), // this carries a string as its data
ThirdState {name: String, counter: u32},
}
Then I store the current app state in an instance current_state : State
. When there is a state change then the current_state
is changed to the next variant. Now here is the important point for the question: The data which is attached to the states is partially carried over. For example, one could image that when the state changes from the second to the third then the name
of ThirdState
is taken from the data of SecondState
. That is, data moves when switching from one enum variant to the next.
Now here is the problem: In reality, the current_state
is inside an tokio::sync::RwLock
, because this is all inside a web API. But then the WriteGuard gives me only a mutable reference and I can't move data.
Here is a minimal (non)-working example. (Without RwLock
, just using a mutable reference to illustrate the problem.)
struct VoteResults {
choiceOne: u32,
choiceTwo: u32,
choiceThree: u32,
}
enum State {
VoteResultsProcessed(VoteResults),
VoteResultsPublished(VoteResults),
}
fn publish_voteresults(state: &mut State) -> Result<(),&'static str> {
match state {
State::VoteResultsProcessed(voteresults) => {
state = State::VoteResultsPublished(voteresults);
Ok(())
}
State::VoteResultsPublished(_) => Err("results already published")
}
}
I have a mutable reference to the enum... so I feel like I should be able to do this variant change with a move of data. I mean, it's all "safe". But I don't see how to do it?
Any help is appreciated.