1

Please someone explain the code below and how can it be unsafe and why is borrowchecker complaining here? I am very new to rust and I come from a little bit of c/c++ background.

fn test(a: &mut [i32], place: usize) -> i32 {
    a[place] /= 2;
    return a[place];
}


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

    let b = test(&mut values, values.len() / 2); // compiler gives error on values.len()

}

Why does it work with first assigning a variable with values.len()/2 and passing that to the function?

ankit
  • 171
  • 1
  • 1
  • 11
  • Does this answer your question? [Cannot borrow as mutable because it is also borrowed as immutable](https://stackoverflow.com/questions/47618823/cannot-borrow-as-mutable-because-it-is-also-borrowed-as-immutable) – Netwave May 14 '22 at 12:32

1 Answers1

4

The problem occurs because you are trying to do two different things to values in two different argument positions and the current Rust implementation is not smart enough to determine that this use case is not problematic.

You can fix this by doing this instead:

fn test(a: &mut [i32], place: usize) -> i32 {
    a[place] /= 2;
    return a[place];
}
 
fn main() {
    let mut values = vec![1, 2, 3, 4];
    let l = values.len() / 2;
    let b = test(&mut values, l);
}
hkBst
  • 2,818
  • 10
  • 29
  • two different things mean trying to pass mutable refrence and calling len function right? Thanks for the answer btw. Rust still has a long way to go if It can't handle these kind of things. – ankit May 14 '22 at 13:00
  • 1
    @ankit: Yes, the len function requires its own immutable borrow, and you also want to pass a mutable borrow. – hkBst May 14 '22 at 13:02