Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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);
like image 404
x2bool Avatar asked Nov 21 '15 14:11

x2bool


1 Answers

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

like image 53
antoyo Avatar answered Dec 01 '22 14:12

antoyo