首页 > 解决方案 > 对具有生命周期说明符和 impl 特征的结构的可变引用的生命周期问题

问题描述

我正在尝试将可变引用传递给一个Container结构,该结构包含生命周期为'a. 由于可变引用的寿命通常不如容器本身的寿命长'static,例如在我的示例中可能具有'b. 我尝试指定它'a可以'b使用'a: 'b语法。但是,生成的代码不会编译并带有神秘的错误消息。

这里出了什么问题?我该如何解决?

这是我的最小工作示例:

// Example container with a lifetime
struct Container<'a> {
    sequence: &'a [usize],
}

impl<'a> Container<'a> {
    // Returns an Iterator which holds a reference to the container to iterate over
    fn get_iterator(&mut self) -> ContainerIterator<'a, '_> {
        ContainerIterator {
            container: self,
            index: 0,
        }
    }
}

// Iterator which holds a reference to the Container where 'b may outlive 'a
struct ContainerIterator<'a, 'b>
where
    'b: 'a,
{
    container: &'a mut Container<'b>,
    index: usize,
}

// Simple iterator implementation as an example
impl<'a, 'b> Iterator for ContainerIterator<'a, 'b> {
    type Item = usize;
    fn next(&mut self) -> Option<usize> {
        if self.index >= self.container.sequence.len() {
            None
        } else {
            Some(self.container.sequence[self.index])
        }
    }
}
impl<'a, 'b> ExactSizeIterator for ContainerIterator<'a, 'b> {}

// This is the function where things go wrong - it should return an iterator which maps the outputs of the `ContainerIterator`
fn get_iterator<'a, 'b: 'a>(
    container: &'a mut Container<'b>,
) -> impl ExactSizeIterator<Item = usize> + 'a {
    container.get_iterator().map(|index| index * 2)
}

fn main() {
    // Container with 'static data and some example code
    let mut container = Container {
        sequence: &[1, 2, 3, 4, 5],
    };
    let output: Vec<_> = get_iterator(&mut container).collect();
    dbg! {output};
}

这是生成的编译器错误,我不知道如何解释或解决:

error[E0623]: lifetime mismatch
  --> src/main.rs:42:15
   |
40 |     container: &'a mut Container<'b>,
   |                ---------------------
   |                |
   |                these two types are declared with different lifetimes...
41 | ) -> impl ExactSizeIterator<Item = usize> + 'a {
42 |     container.get_iterator().map(|index| index * 2)
   |               ^^^^^^^^^^^^ ...but data from `container` flows into `container` here

标签: rustcompiler-errorslifetime

解决方案


推荐阅读