I have an immutable data structure, and an update function that takes ownership of the data structure and returns a new data structure:
enum Immutable {
Item(i32)
}
fn update(imm: Immutable) -> Immutable {
match imm {
Immutable::Item(x) => Immutable::Item(x + 1)
}
}
I need to store the data structure in a mutable field of a container:
struct State {
item: Immutable
}
I want to write an imperative update function for State
that calls the function updater:
fn update_mut(st: &mut State) -> () {
let mut owned = Immutable::Item(42); // junk
std::mem::swap(&mut st.item, &mut owned);
st.item = update(owned);
}
This code works, but it seems sily to use mem::swap
and allocate a junk object. I would really like to write:
fn update_mut_type_error(st: &mut State) -> () {
let mut owned = Immutable::Item(42); // junk
std::mem::swap(&mut st.item, &mut owned);
st.item = update(st.item); // type error
}
Is there any way to address this? Or, do I have to use mem::swap
here, even though it seems spurious.