首页 > 解决方案 > 临时值在自定义结构中的寿命不够长

问题描述

我正在尝试使用 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为结构中的u16atxy字段,X那么它可以工作。这个想法是我想从函数中返回向量的一部分,不要介意值或指针。

如果我尝试返回一个值向量,我会得到:

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

标签: rust

解决方案


推荐阅读