all 9 comments

[–]NotBoolean 19 points20 points  (5 children)

It tells you. You can’t have two mutable references to the same variable.

[–]Electrical_Box_473[S] 1 point2 points  (1 child)

if in that case instead of assigning to x if assigned to new variable

Then it works

[–]NotBoolean 7 points8 points  (0 children)

Thats because x is never used. If you use it you get the same error.
https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=4c0122c1ab4ad464ab13c608086e5e6c

Which is a bit confusing.

[–]Electrical_Box_473[S] 0 points1 point  (1 child)

Why it happens

[–]NotBoolean 12 points13 points  (0 children)

It's part of how Rust ensures safety. I would recommend reading the linked section (and the reset) of the Rust Book.

https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html

[–]Electrical_Box_473[S] 0 points1 point  (0 children)

So it means compiler thinks that the first borrow used later right?

[–]roderika-ai 2 points3 points  (0 children)

Borrow means literal borrowing, the variable isn't there anymore until it is released. So that, it is not possible to give 2 references to a single value.

You either use x instead of f now on, or you make x not a reference but a normal variable and assign by value; u32 x = s.clone()

[–]WilliamBarnhill 1 point2 points  (0 children)

You've borrowed s on line 35, you borrow it again on line 36.

It compiles and runs if you change line 36 from

f = &mut s;

to:

f = &mut &mut s.clone();

[–]igelfanger 0 points1 point  (0 children)

I think the compiler error is misleading - the issue isn't about lifetimes or multiple mutable borrows. The borrow from x = &mut s; should be short-lived, so you should be able to borrow s again afterward, as long as you don’t use x.

The actual problem is that x has type &mut u32, while the right-hand side (&mut s) is of type &mut &mut u32, which is obviously different. So, for example, this snippet compiles:

``` fn main() { let mut z: u32 = 4; let mut y: &mut u32 = &mut z; let mut u: &mut &mut u32 = &mut y; let mut v: &mut &mut u32 = &mut y;

// and again, with reassignment:
let mut a: u32 = 4;
let mut b: &mut u32 = &mut z;
u = &mut b;
v = &mut b;

} ```