使用Rust

时间:2017-09-01 14:00:05

标签: 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_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() {}

应该可以做这样的事情,因为数据数组与哈希映射中的引用一样长。但是,当尝试迭代数据数组中的对象时,我得到以下错误

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
  --> src/main.rs:29:18
   |
29 |         for d in &self.data {
   |                  ^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 28:5...
  --> src/main.rs:28:5
   |
28 | /     fn build_index(&mut self) {
29 | |         for d in &self.data {
30 | |             self.by_attribute1.insert(d.attribute1, &d);
31 | |         }
32 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:29:18
   |
29 |         for d in &self.data {
   |                  ^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 13:1...
  --> src/main.rs:13:1
   |
13 | / impl<'a> IndexedVector<'a> {
14 | |     pub fn new() -> Self {
15 | |         let mut res = Self {
16 | |             data: vec![
...  |
32 | |     }
33 | | }
   | |_^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:30:53
   |
30 |             self.by_attribute1.insert(d.attribute1, &d);
   |                                                     ^^

0 个答案:

没有答案