Error when try modify values in a variable outside scope!

Here is the code has been simplified since the original code is quite long:

fn main() {
    let mut temp: Vec<&str> = Vec::new();
    let arr = vec![
        "1".to_string(),
        "2".to_string(),
        "3".to_string(),
        "4".to_string(),
    ];
    for ele in arr {
        let test = ele;
        let next_test = test.as_str();
        temp.push(next_test);
    }
    println!("{:?}", temp);
}

And received:

error[E0597]: `test` does not live long enough
  --> src/main.rs:11:25
   |
11 |         let next_test = test.as_str();
   |                         ^^^^^^^^^^^^^ borrowed value does not live long enough
12 |         temp.push(next_test);
   |         -------------------- borrow later used here
13 |     }
   |     - `test` dropped here while still borrowed

Actually values in arr vector very complex, i want handle it in for loop and move them to temp vector, any one can help? Sorry about my English.

for consumes the arr, so the elements in the arr don't exist after you give it to the for. You can prevent this by iterating over references to the contents of arr like so:

-    for ele in arr {
+    for ele in &arr {
+    //         ^

Playground. arr is still around after the loop now, because for consumes just the reference &arr instead. If this doesn't work for your use case, we'll probably need more details.

1 Like

What you want is probably this:

for ele in &arr {
     temp.push(ele);
}

The point is that if you borrow inside the loop, the lifetime is restricted to inside the loop. Hence, you get the "dropped while still borrowed" warning.

2 Likes

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.