Does rust new versions change limit on using borrowed variable?

With code

fn main() {
    let mut y = 20;
    let m1 = &mut y;
    let z = y;
    println!("{}", y);
}

Using rustc 1.1.0 (35ceea399 2015-06-19), it shows error:

src/main.rs:4:9: 4:10 error: cannot use `y` because it was mutably borrowed
src/main.rs:4     let z = y;
                      ^
src/main.rs:3:19: 3:20 note: borrow of `y` occurs here
src/main.rs:3     let m1 = &mut y;
                                ^
src/main.rs:5:20: 5:21 error: cannot borrow `y` as immutable because it is also borrowed as mutable
src/main.rs:5     println!("{}", y);
                                 ^

But using rustc 1.81.0 (eeb90cda1 2024-09-04), it is ok

warning: unused variable: `m1`
 --> src/main.rs:3:9
  |
3 |     let m1 = &mut y;
  |         ^^ help: if this is intentional, prefix it with an underscore: `_m1`
  |
  = note: `#[warn(unused_variables)]` on by default

warning: unused variable: `z`
 --> src/main.rs:4:9
  |
4 |     let z = y;
  |         ^ help: if this is intentional, prefix it with an underscore: `_z`

warning: `bbbb` (bin "bbbb") generated 2 warnings
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.09s
     Running `target/debug/bbbb`
20

Yes. This is so-called nonlexical lifetimes in action. The borrow checker can, and is supposed to, become smarter in new versions of the compiler so that more valid (soundly typed) programs are accepted.

5 Likes

Here's an announcement about it.

1 Like

Thanks. :grinning:

OK, thanks :slight_smile: :grinning:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.