嵌套结构中的生命周期

时间:2017-11-24 16:45:08

标签: struct nested rust lifetime

我有一个包含子结构向量的结构,每个子结构都需要一些相当大的数据结构用于计算,这些结构可能与其他子结构共享,也可能不共享。因此,上层结构拥有这些数据结构并且子结构仅具有引用是有意义的。试图为此编写一个构造函数,我遇到了一个生命周期错误,我无法解读。

最小的非工作示例:

use std::collections::HashMap;

struct SuperStruct<'a> {
    hash_map: HashMap<String, Vec<f64>>,
    substructs: Vec<SubStruct<'a>>,
}

impl<'a> SuperStruct<'a> {
    fn new(vectors: Vec<Vec<f64>>) -> SuperStruct<'a> {
        let mut substructs = vec![];
        let mut hash_map = HashMap::new();
        let mut k = 0;

        for vector in vectors {
            substructs.push(SubStruct { reference: &vector });
            hash_map.insert(format!("vec_{}", k), vector);
            k += 1;
        }
        SuperStruct{ hash_map, substructs }
    }
}

struct SubStruct<'a> {
    reference: &'a Vec<f64>,
}

fn main() {
    // println!("Hello");
}

尝试编译此结果会导致以下错误:

error[E0597]: `vector` does not live long enough
  --> moo.rs:15:53
   |
15 |             substructs.push(SubStruct { reference: &vector });
   |                                                     ^^^^^^ does 
not live long enough
...
18 |         }
   |          - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on 
the impl at 8:1...
  --> moo.rs:8:1
   |
8  | / impl<'a> SuperStruct<'a> {
9  | |     fn new(vectors: Vec<Vec<f64>>) -> SuperStruct<'a> {
10 | |         let mut substructs = vec![];
11 | |         let mut hash_map = HashMap::new();
...  |
20 | |     }
21 | | }
   | |_^

我打赌我错过了一些非常明显的东西,但它是什么?

0 个答案:

没有答案