4

What is the difference between assign after binding to var and direct assign a &Vec.

let mut v2 = &vec![1,2,3];

let tv = &vec![2,3,4];
v2 = tv;

// different from
// v2 = &vec![2, 3, 4];  // uncomment this will error

println!("{:?}", v2);

borrow checker:

error[E0716]: temporary value dropped while borrowed
  --> examples\demo.rs:27:11
   |
27 |     v2 = &vec![2, 3, 4];
   |           ^^^^^^^^^^^^^- temporary value is freed at the end of this statement
   |           |
   |           creates a temporary which is freed while still in use
...
30 |     println!("{:?}", v2);
   |                      -- borrow later used here
kmdreko
  • 42,554
  • 6
  • 57
  • 106
BruceChar
  • 83
  • 1
  • 5
  • `creates a temporary which is freed while still in use` is the key. The `Vec` has no variable which ownes it, and Rust wont allow an dangling reference to a temporary after that line. – Brady Dean Mar 03 '21 at 02:38
  • 1
    Does this answer your question? [Why is it legal to borrow a temporary?](https://stackoverflow.com/questions/47662253/why-is-it-legal-to-borrow-a-temporary) Actually, while a good reference, the answers there don't really go over why the second form isn't allowed. – kmdreko Mar 03 '21 at 02:39
  • 1
    This appears to be an arbitrary decision with respect to [temporary lifetime extension](https://doc.rust-lang.org/1.48.0/reference/destructors.html#temporary-lifetime-extension). The lifetime of the temporary in a `let` statement can be extended. That's why the commented out code fails to compile. If you make that `let v2 = ...;` it will compile again. – IInspectable Mar 03 '21 at 18:14

0 Answers0