2

I need to save a reference to a field of an Iterator in the struct which is returned by the next-method. However the compiler cannot infer an appropriate lifetime for the borrow expression. Is this possible in the current release of Rust an how can I do it?

In the following is a reduced code snippet and the full error message:

use std::collections::HashMap;

struct CellDataRef<'a> {
    value: &'a str,
}

struct Row<'a> {
    data_ref: &'a HashMap<String, CellDataRef<'a>>,
}

struct TableIterator<'a> {
    data: HashMap<String, CellDataRef<'a>>,
}

impl<'a> Iterator for TableIterator<'a> {
    type Item = Row<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        Some(Row {
            data_ref: &self.data,
        })
    }
}

Compiler error:

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
  --> src/lib.rs:20:23
   |
20 |             data_ref: &self.data,
   |                       ^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 18:5...
  --> src/lib.rs:18:5
   |
18 |     fn next(&mut self) -> Option<Self::Item> {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
  --> src/lib.rs:20:23
   |
20 |             data_ref: &self.data,
   |                       ^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 15:6...
  --> src/lib.rs:15:6
   |
15 | impl<'a> Iterator for TableIterator<'a> {
   |      ^^
note: ...so that the types are compatible
  --> src/lib.rs:18:46
   |
18 |       fn next(&mut self) -> Option<Self::Item> {
   |  ______________________________________________^
19 | |         Some(Row {
20 | |             data_ref: &self.data,
21 | |         })
22 | |     }
   | |_____^
   = note: expected `Iterator`
              found `Iterator`

0 Answers0