rust - 对具有生命周期说明符和 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
解决方案
推荐阅读
- css - sass-loader 不生成 CSS
- firebase - ScopedModel 与 Firestore 添加重复记录
- excel - VBA 将公式转换为注释
- reactjs - 使用 react 与 angular 构建 ionic 4 应用程序之间的性能差异
- android - 我想突出显示 ArrayList 的单个单词
- jsp - 如何使用jsp中的post方法将隐藏的表单字段传递给servlet过滤器的doFilter方法?
- javascript - 如何在 React js 中修复“相同的道具传递给孩子”?
- performance - LINQ AsNoTracking 运行缓慢
- servicestack - 覆盖特定端点上的 AutoQuery MaxLimit
- javascript - 从其他组件中的服务访问数据