Clinton
Clinton

Reputation: 23135

How can I mutate a parameter that was passed by move?

My understanding is if I have a function like:

fn f(x: Vec<u32>) -> (some result)

f takes ownership of x. f is now responsible for x's destruction.

If this is the case, can I mutate x, and if so how? To get a mutable iterator to x requires a &mut, which I don't have.

It seems reasonable that I should be able to mutate a variable I now have ownership over without any ill effects I'm just not sure how. The calling function has relinquished ownership of x to f, so it shouldn't care what happens to it.

Perhaps I could change the type f to f(x: &mut Vec<u32>), but I don't really want to do that for a variety of reasons, for example it prevents chaining functions in a natural way like f(g(x)), and also if my "(some result)" is something other than a Vec<u32> (like a type that contains a Vec<u32>) then I'll have to split the function into two and ensure the caller does what they're supposed to do.

Upvotes: 3

Views: 761

Answers (2)

Svetlin Zarev
Svetlin Zarev

Reputation: 15683

You should declare the x argument to be mutable: mut x: Whatever

fn main() {
    let x = vec![];
    mutate(x);
}

fn mutate(mut x: Vec<u32>) {
    x.push(1);
}

Upvotes: 5

Stargateur
Stargateur

Reputation: 26727

You could shadow x:

fn main() {
    let x = vec![];
    mutate(x);
}

fn mutate(x: Vec<u32>) {
    let mut x = x;
    // ...
}

Upvotes: 3

Related Questions