使用Rust中的成员HashMap索引结构成员Vec

使用Rust中的成员HashMap索引结构成员Vec,rust,lifetime,borrow-checker,Rust,Lifetime,Borrow Checker,我想将一些对象存储在Vec中,并通过字段的值有效地检索它们。实际上,我希望通过多个字段对其进行索引,否则我可以只使用HashMap。以后不会更改Vec或对象字段 use std::collections::HashMap; pub struct Data { attribute1: i64, attribute2: String, } pub struct IndexedVector<'a> { data: Vec<Data>, by_

我想将一些对象存储在
Vec
中,并通过字段的值有效地检索它们。实际上,我希望通过多个字段对其进行索引,否则我可以只使用
HashMap
。以后不会更改
Vec
或对象字段

use std::collections::HashMap;

pub struct Data {
    attribute1: i64,
    attribute2: String,
}

pub struct IndexedVector<'a> {
    data: Vec<Data>,
    by_attribute1: HashMap<i64, &'a Data>,
}

impl<'a> IndexedVector<'a> {
    pub fn new() -> Self {
        let mut res = Self {
            data: vec![
                Data {
                    attribute1: 1,
                    attribute2: "foo".into(),
                },
            ],
            by_attribute1: HashMap::new(),
        };
        res.build_index();
        res
    }

    fn build_index(&mut self) {
        for d in &self.data {
            self.by_attribute1.insert(d.attribute1, &d);
        }
    }
}

fn main() {}
使用std::collections::HashMap;
发布结构数据{
属性1:i64,
属性2:字符串,
}
发布结构IndexedVector,
}
恳求{
pub fn new()->Self{
让mut res=Self{
数据:vec[
资料{
属性1:1,
attribute2:“foo”.into(),
},
],
按属性1:HashMap::new(),
};
res.build_index();
物件
}
fn构建索引(&mut self){
对于d in和self.data{
自身属性1.插入(d.属性1和d);
}
}
}
fn main(){}
这样做应该是可能的,因为数据数组与哈希映射中的引用一样存在。但是,当尝试迭代数据数组中的对象时,我得到以下错误

错误[E0495]:由于需求冲突,无法推断借用表达式的适当生存期
-->src/main.rs:29:18
|
29 |用于d in和自我数据{
|                  ^^^^^^^^^^
|
注意:首先,生命周期不能超过方法体上28:5定义的匿名生命周期#1。。。
-->src/main.rs:28:5
|
28 |/fn构建索引(&mut self){
29 | |对于d in和self.data{
30 | | self.by|u attribute1.插入(d.attribute1,&d);
31 | |         }
32 | |     }
| |_____^
注意:…这样引用就不会超过借用的内容
-->src/main.rs:29:18
|
29 |用于d in和自我数据{
|                  ^^^^^^^^^^
注意:但是,生存期必须对impl上定义的13:1的生存期“a”有效。。。
-->src/main.rs:13:1
|
13 |/impl{
14 | | pub fn new()->Self{
15 | |让mut res=Self{
16 | |数据:vec[
...  |
32 | |     }
33 | | }
| |_^
注意:…这样引用就不会超过借用的内容
-->src/main.rs:30:53
|
30 |自身属性1.插入(d.属性1和d);
|                                                     ^^
这是中“有一种特殊情况,您可以创建一个带有自身引用的类型”的变体。问题是,您无法向
Vec添加值,甚至在索引后无法移动该值。这是一种编译方法,但不太可能执行您想要的操作。