I have a function that takes ownership of some data, modifies it destructively, and returns it.
fn transform(s: MyData) -> MyData {
todo!()
}
In some situations, I have a &mut MyData
reference. I would like to apply transform
to &mut MyData
.
fn transform_mut(data_ref: &mut MyData) {
*data_ref = transform(*data_ref);
}
However, this causes a compiler error.
error[E0507]: cannot move out of `*data_ref` which is behind a mutable reference
--> src/lib.rs:10:27
|
10 | *data_ref = transform(*data_ref);
| ^^^^^^^^^ move occurs because `*data_ref` has type `MyData`, which does not implement the `Copy` trait
I considered using mem::swap
and mem::replace
, but they require that you already have some valid value to put into the reference before taking another one out.
Is there any way to accomplish this? MyData
doesn't have a sensible default or dummy value to temporarily stash in the reference. It feels like because I have exclusive access the owner shouldn't care about the transformation, but my intuition might be wrong here.