x2bool
x2bool

Reputation: 2906

How to pass a mutable function parameter as argument to another function?

Why does Rust prevent this code from compiling, with the error: "cannot borrow immutable local variable arr as mutable"? How to pass the vector into another function as mutable reference?

let mut vec = vec![0];

fn bar(vec: &mut Vec<i32>) {
    // some code here
}

fn foo(vec: &mut Vec<i32>) {
    bar(&mut vec);
}

foo(&mut vec);

Upvotes: 13

Views: 13015

Answers (1)

antoyo
antoyo

Reputation: 11933

You don't need to use &mut in this case:

let mut vec = vec![0];

fn bar(vec: &mut Vec<i32>) {
    // some code here
}

fn foo(vec: &mut Vec<i32>) {
    bar(vec);
}

foo(&mut vec);

because vec is already a &mut Vec<i32>.

Upvotes: 19

Related Questions