0

I am trying to place a string reference into a vector. The values are in the same scope. Why does the following code result in a borrowing error?

fn main() {
    let val: u32 = 0;
    let ref_of_val = &val;

    let mut record = Vec::new();
    let string_of_ref_of_val: String = ref_of_val.to_string();
    record.push(&string_of_ref_of_val);
    record.clear();
}

The resulting error:

error[E0597]: `string_of_ref_of_val` does not live long enough
 --> src/main.rs:7:18
  |
7 |     record.push(&string_of_ref_of_val);
  |                  ^^^^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
8 |     record.clear();
9 | }
  | - `string_of_ref_of_val` dropped here while still borrowed
  |
  = note: values in a scope are dropped in the opposite order they are created

If I push record.push(string_of_ref_of_val); instead, everything ends up OK. Why is this the case? What is a possible solution?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ZNackasha
  • 755
  • 2
  • 9
  • 29
  • Can you expand on what you find confusing about the error message: *"values in a scope are dropped in the opposite order they are created"*? That explains the problem. – Shepmaster Apr 23 '18 at 21:41
  • 2
    I believe your question to already be answered by the answers of [How do I add references to a vector when the borrowed values are created after the vector?](https://stackoverflow.com/q/44987555/155423). If you disagree, please [edit] your question to explain why it is different. Otherwise, we can mark this as already answered. – Shepmaster Apr 23 '18 at 21:43
  • 1
    @Shepmaster thank you for the link, it completely answers my question. – ZNackasha Apr 23 '18 at 21:45

0 Answers0