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);
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With