临时值在定制结构上的寿命不足

时间:2018-11-08 17:10:48

标签: rust

我正在尝试使用Serde从JSON解析具有客户结构的数组。我简化了示例以重现该问题,但想法是相同的-我有带有客户结构的向量:

#[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);
}

我得到了错误:

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

如果我在String结构的u16x字段中将y更改为X,那么它将起作用。我的想法是我想从函数返回向量的某些部分,不要介意值或指针。

如果我尝试返回值的向量,则会得到:

14 |         y.push(*i);
   |                ^^ cannot move out of borrowed content

0 个答案:

没有答案
相关问题