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?