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