0

I'm trying to parse an array with customer structures from JSON using Serde. I simplified the example to reproduce the problem, but the idea is the same - I have vector with customer structs:

#[derive(Debug)]
struct X {
    x: String,
    y: String,
}

fn get_d<'a>() -> Vec<&'a X> {
    let mut y: Vec<&X> = vec![];
    let x = vec![
        &X {
            x: String::new(),
            y: String::new(),
        },
        &X {
            x: String::new(),
            y: String::new(),
        },
    ];
    for i in x.iter() {
        y.push(i);
    }

    y
}

fn main() {
    let d = get_d();
    println!("{:?}", d);
}

I got the error:

error[E0597]: borrowed value does not live long enough
  --> src/main.rs:10:10
   |
10 |           &X {
   |  __________^
11 | |             x: String::new(),
12 | |             y: String::new(),
13 | |         },
   | |_________^ temporary value does not live long enough
...
18 |       ];
   |        - temporary value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 7:10...
  --> src/main.rs:7:10
   |
7  | fn get_d<'a>() -> Vec<&'a X> {
   |          ^^
   = note: consider using a `let` binding to increase its lifetime

If I change String to u16 at x and y fields in the X struct then it works. The idea is I want to return some part of the vector from the function, nevermind values or pointers.

If I try to return a vector of values I get:

14 |         y.push(*i);
   |                ^^ cannot move out of borrowed content
Shepmaster
  • 274,917
  • 47
  • 731
  • 969
James May
  • 995
  • 1
  • 13
  • 30
  • [Return a vector of values](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=92c738dd64712afd928d510f57e91626) – Shepmaster Nov 08 '18 at 18:16
  • I'd say the real question here is: "Why does it work when [replacing the `String`s with `u16`s](https://play.integer32.com/?version=stable&mode=release&edition=2015&gist=1ee53f0144306fecf751c680dea89a0f)". I would expect the references to the `X` temporaries to be too short-lived too… – Jmb Nov 09 '18 at 07:39
  • While the question has an answer it does not highlight your mistake, that was creating a vector of pointers and allocate the pointers inside the `get_d` function. You should instead move the structs out or allocate them on the heap using Box. ```fn get_d() -> Vec { vec![ X { x: String::new(), y: String::new(), }, X { x: String::new(), y: String::new(), }, ]; }``` – Eduardo Braun Nov 09 '18 at 10:29

0 Answers0