0

The following code does NOT compile (which is correct, since there can't be two mutable references to the same value n at the same time):

let mut n=5;

let p1 = &mut n;
*p1 = 10;

let p2 = &mut n;
*p2 = 20;

*p1 = 30;

Why, on the contrary, if I use let p2 = &mut *p1, instead of let p2 = &mut n it compiles correctly and works?

let mut n=5;

let p1 = &mut n;
*p1 = 10;

let p2 = &mut *p1;
*p2 = 20;

*p1 = 30;

I expected the second code would not compile, too. Shouldn't n and *p1 be the same thing? It looks like the compiler considers them as two different variables, so that multiple mutable references are allowed, but I don't understand why.

0 Answers0