Firstly, I am still learning Rust, so I may be misunderstanding or overcomplicating some of this.
Is there a function/method or idiom of in-place substitution of a value (through a &mut reference) with another value with transfer of ownership of some members of the original value (see example below)?
Consider a situation in which a value needs to be replaced, but some of the contents of the value is expensive to reallocate/duplicate. Ideally, ownership of the original value could be obtained and transferred into the new value, which would then be assigned to the original reference, but this would leave the original value invalid while this is in progress. Note that for some values (such as
Vecs), empty values do not actually require any memory allocation, so an empty value can be
std::mem::replaced in with relatively negligible cost, but this may not always be possible for all types.
Here is an example solution that I wrote (see
try_mutate at the bottom):
Note: it may not be technically correct. I have used unsafe Rust and am only new to this, so I may have done something stupid.
Note 2: I am using
Strings as a placeholder for a data type that can be expensive to allocate, but obviously in this case the
Strings could be replaced with empty strings temporarily.
Is there a better idiom or similar existing functions that would be more appropriate to use?