I have seen std::mem::swap
and std::mem::replace
, I'm looking for something similar to replace a memory location with a new value computed based on consuming the old value. I would like to take the value (like with std::mem::take
) but not leave a Default in it's place, but replace it immediately with a new value created based on the value I took.
I have written a rough example:
struct StateA {
s: String
}
struct StateB {
i: usize
}
enum State {
A(StateA),
B(StateB)
}
struct Doer {
state: State
}
impl Doer {
pub fn do_thing(&mut self) {
// Here I have a problem, code like this doesn't exist!
std::mem::update(&mut self.state, move |state| {
match state {
State::A(state_a) => State::B(do_a_thing(state_a)),
State::B(state_b) => State::A(do_b_thing(state_b))
}
})
}
}
// These functions should not be modified, I'd like to assume that they are from external dependencies
fn do_a_thing(a: StateA) -> StateB {
StateB {
i: a.s.len()
}
}
fn do_b_thing(b: StateB) -> StateA {
StateA {
s: b.i.to_string()
}
}
(Here is a Rust Playground link but the code doesn't compile, obviously)
I could make my state
Option
al, I could also add another enum variant as an intermediate Default value. Is there a way without doing those things?