0
votes

How can a function with a borrowed mutable reference call a second function with the same borrowed mutatble reference?

fn main() {
    let mut a = vec![0, 1, 2, 3, 4];
    
    first_function(&mut a);
    
    println!("{:?}", a);
}

fn first_function(a: &mut Vec<i32>) {
    println!("...first function");
    a[0] = 5;
    second_function(&mut a);
}

fn second_function(a: &mut Vec<i32>) {
    println!("...second function");
    a[2] = 6;
}

The compiler errors are normally very helpful, but I don't understand this one;

error[E0596]: cannot borrow `a` as mutable, as it is not declared as mutable
  --> src/main.rs:12:21
   |
9  | fn first_function(a: &mut Vec<i32>) {
   |                   - help: consider changing this to be mutable: `mut a`
...
12 |     second_function(&mut a);
   |                     ^^^^^^ cannot borrow as mutable

... here's a link to the code in Rust Playground

1

1 Answers

3
votes

By writing &mut a, you’re trying to take a mutable reference to a, not to what its value references – it would be a &mut &mut Vec<i32>. a’s value is already the mutable reference you want:

second_function(a);

updated playground