I'm trying to write a function with this signature, without using clone()
or allocating a new vector:
fn mapVec(f: Fn(T) -> T, x: Vec<T>) -> Vec<T>
In my head, this seems to be doable. For each element in x
, we pass it to f
, with f
taking ownership of it. We then produce a return value, and then as f
has taken ownership this passed value, it destroys it if necessary. We then place the return value in place back into the vector. As we've taken ownership of x
, we're allowed to modify it, and then we can return it to the caller.
My attempt was the following:
for e in x.iter_mut() {
*e = f(e);
}
return x;
But unfortunately f
expects a T
, not a &mut T
.
I don't want to change the signature of mapVec
to for example, use mutable functions, I want this to look like a pure function from the outside if possible, just taking advantage of mutation on the inside because we can get away with it because the caller has passed us ownership of the object.