Sergey Kamardin
Sergey Kamardin

Reputation: 1730

How to reference values from one Vec to another?

I'm just trying to make something like this:

fn main() {
    let mut points: Vec<(&str, &str)> = Vec::new();
    let existing: Vec<(String, String)> = Vec::new();

    for t in existing {
        points.push((&t.0[..], &t.1[..]));
    }
}

And got an error:

error[E0597]: `t.0` does not live long enough
 --> src/main.rs:6:23
  |
5 |     for t in existing {
  |         - binding `t` declared here
6 |         points.push((&t.0[..], &t.1[..]));
  |         ------        ^^^ borrowed value does not live long enough
  |         |
  |         borrow later used here
7 |     }
  |     - `t.0` dropped here while still borrowed

How could I do this in Rust?

Upvotes: 0

Views: 275

Answers (1)

oli_obk
oli_obk

Reputation: 31263

Lifetimes start at the variable declaration. Since your points variable is created before the existing variable, points is not allowed to have any references to existing, because existing will be dropped before points.

The second issue is that you are iterating over values, which will further limit the lifetime of the Strings to the loop-body.

The easy solution is to swap the two declarations and change the loop to iterate over references instead of values:

let existing : Vec<(String, String)> = Vec::new();
let mut points : Vec<(&str, &str)> = Vec::new();

for t in &existing {
    points.push((&t.0, &t.1));
}

Upvotes: 6

Related Questions