Modify mutable vectors in a function


#1

I am going through the Rust Book and as noted there I have stumbled over the ownership concept. I have worked through the basic examples given in the Book and the next thing I tried was to pass mutable vectors to a function and modify them within the function. Here is my attempt:

fn foo(mut v1: &Vec<i32>, mut v2: &Vec<i32>) {
    v1.push(4);
    v2.push(4);
}

fn main() {

    let mut v1 = vec![1, 2, 3];
    let mut v2 = vec![1, 2, 3];

    println!("{} {}", v1[0], v2[2]);

}

This gives me the following error:

src/main.rs:4:5: 4:7 error: cannot borrow immutable borrowed content `*v1` as mutable
src/main.rs:4     v1.push(4);
                  ^~
src/main.rs:5:5: 5:7 error: cannot borrow immutable borrowed content `*v2` as mutable
src/main.rs:5     v2.push(4);

How can I make this happen? Thanks in advance.


#2

Even though v1 and v2 are declared as mut, they are still &Vec. &Vec as a type is an immutable reference, and can’t be mutated even if the variable holding that reference can.

What you want is the reference itself to be mutable, not just a mutable variable. Try &mut Vec<i32>:

fn foo(v1: &mut Vec<i32>, v2: &mut Vec<i32>) {
    v1.push(4);
    v2.push(4);
}

fn main() {
    let mut v1 = vec![1, 2, 3];
    let mut v2 = vec![1, 2, 3];

    println!("{} {}", v1[0], v2[2]);
}

#3

This makes sense, thank you so much.

[edit]

Sure enough &mut is explained in the following section of the book. :blush: