Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Release borrowing in Rust [duplicate]

I'm trying Rust and have some issues with understanding "borrowing".

fn main() {
    let mut x = 10;
    let mut a = 6;
    let mut y = &mut x;

    *y = 6;
    y = &mut a;

    x = 15;
    println!("{}", x);
}

And I've got an error:

error[E0506]: cannot assign to `x` because it is borrowed
 --> <anon>:9:5
  |
4 |     let mut y = &mut x;
  |                      - borrow of `x` occurs here
...
9 |     x = 15;
  |     ^^^^^^ assignment to borrowed `x` occurs here

error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
  --> <anon>:10:20
   |
4  |     let mut y = &mut x;
   |                      - mutable borrow occurs here
...
10 |     println!("{}", x);
   |                    ^ immutable borrow occurs here
11 | }
   | - mutable borrow ends here

How can I release x from "y-borrowing"?

like image 483
vZ10 Avatar asked Apr 20 '17 15:04

vZ10


1 Answers

This is currently a limitation of the Rust borrow checker, often referred to as "non lexical lifetimes" (NLL). The problem here is that the when you assign a reference to a variable (let mut y = &mut x;) the reference has to be valid for the entire scope of the variable. This means that "x is borrowed" lasts for the entire scope of y. So the compiler doesn't care about the line y = &mut a;!

You can read a lot more (technical) discussion about this here at the tracking issue.

EDIT: non-lexical lifetimes have landed some time ago, so your code should compile fine now.

like image 161
Lukas Kalbertodt Avatar answered Oct 22 '22 17:10

Lukas Kalbertodt