Understanding of reference life time in Rust

我是研究僧i 提交于 2021-01-29 00:34:54

问题


I'm a new Rust user and I'm reading a book The Complete Rust Programming Reference Guide. In the book there is an example:

fn main() {
    let mut a = String::from("testing");
    let a_ref = &mut a;
    a_ref.push('!');

    println!("{}", a);
}

The book states the code will generate an error.

However, on my local machine, I can run it without any issue. Is this because I'm using a newer Rust compiler [rustc 1.41.0-nightly (412f43ac5 2019-11-24)] and the code doesn't work on older ones? I've read some chapters of the official Rust book. As I understand, the lifetime of the reference a_ref ends at its last usage, which is a_ref.push('!');. After that a_ref is gone and a should be able to be used without issue. Is my understanding correct?


回答1:


The most likely occurrence is that the book you're reading is teaching lifetimes disregarding non-lexical-lifetimes. This would make sense; lexical lifetimes are the most straightforward to understand.

Running the following will revert to prior to when non-lexical-lifetimes came around:

rustup default 1.30

This will revert rustc to prior to version 1.31, which according to this document is the minimum version for nll.

Running this results in the exact same error as shown:

> cargo run
   Compiling forum_examples v0.1.0 (C:\Users\user\Desktop\forum_examples)
error[E0502]: cannot borrow `a` as immutable because it is also borrowed as mutable
 --> src\main.rs:6:20
  |
3 |     let a_ref = &mut a;
  |                      - mutable borrow occurs here
...
6 |     println!("{}", a);
  |                    ^ immutable borrow occurs here
7 | }
  | - mutable borrow ends here

error: aborting due to previous error

For more information about this error, try `rustc --explain E0502`.
error: Could not compile `forum_examples`.

To learn more, run the command again with --verbose.

You may choose to use this version of the compiler (Or version 1.35 with 2015 edition) to follow the book to the letter or you may use this rule of thumb to determine why it doesn't compile according to the book but does with the compiler present today: The compiler will drop a reference if it should see that it is no longer needed. In your example, the compiler sees that a_ref is no longer needed afterwards, so it's inserting an implicit drop right after for that. Note that this only works for references, and not for guards, or more complex types involving lifetimes (Especially not anything that could invoke drop code).



来源:https://stackoverflow.com/questions/59206070/understanding-of-reference-life-time-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!