13

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);
1

1 Answer 1

19

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>.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.