Reference chaining?

Hey new to Rust and the concept of borrowing. So it says only one mutable reference is allowed. Why does the following work, aren't those two references? Glad for your help, annotated how i think it works.

    fn f1( p1: &mut [i32]){
//changing the content of the variable received by its SECOND mutable reference
    p1[1]=3;
    
}
fn f2( mut x: &mut [i32]){
//creating another mutable reference to the variable
    f1(&mut x);
    f1(&mut x);
}


fn main() {
//create mutable variable
    let mut a :[i32;5]= [1, 2, 3, 4, 5];
//pass mutable reference into function 
    f2(&mut a);
    println!("{}",a[1]);
}

Generally, the rules that mutable references follow are:

Between any two uses of a mutable reference, no other reference has accessed that variable.

and

The only reference that can access a variable both before and after a mutable reference does so, is the reference that the mutable reference was created from (possibly recursively).

So the reason it works is that the usages of the mutable references do not overlap in a disallowed manner.

1 Like