Is there a clean way to implement a safe function g
that mutates a mutable reference by applying f
on its value without having to implement Clone
or Default
(or any other special trait) for T
? If not, why is or should this not be possible?
Imagine a type T
and a function f
:
fn f(v: T) -> T;
For example:
fn f(mut v: u32) -> u32 {
v += 1;
v
}
The following code is invalid because p
cannot be dereferenced:
fn g(p: &mut T) {
*p = f(*p)
}
I searched and tried many things, but I didn't come up with a safe solution.
For people who are interested for the cases where Clone
and Default
are allowed:
By implementing
Clone
you could do:fn g(p: &mut T) { *p = f(p.clone()) }
By implementing
Default
you could do:fn g(p: &mut T) { let val = core::mem::take(p); core::mem::replace(p, f(val)); }