'"Cannot borrow `*arr` as immutable because it is also borrowed as mutable" in a function call

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hkBst