从迭代器返回切片时,无法推断适当的寿命

  • 本文关键字:返回 迭代器 切片 rust
  • 更新时间 :
  • 英文 :


我有一个简单struct Point {x: f32, y: f32, z: f32}Vec<Point>。我的向量代表3D中数十万行(实际上可能是Vec<Vec<Point>>),因此我跟踪所有行的开始/结尾。

pub struct Streamlines {
    lengths: Vec<usize>,
    offsets: Vec<usize>,  // cumulative sum of lengths
    data: Vec<Point>,
}

我想创建一个非消费迭代器,例如:

for streamline in &streamlines {
    for point in &streamline {
        println!("{} {} {}", point.x, point.y, point.z);
    }
    println!("")
}

我找到了如何实现简单结构的迭代器和进程器?并开始copyi-err,适应:)

impl IntoIterator for Streamlines {
    type Item = &[Point];
    type IntoIter = StreamlinesIterator;
    fn into_iter(self) -> Self::IntoIter {
        StreamlinesIterator {
            streamlines: self,
            it_idx: 0
        }
    }
}
struct StreamlinesIterator {
    streamlines: &Streamlines,
    it_idx: usize
}
impl Iterator for StreamlinesIterator {
    type Item = &[Point];
    fn next(&mut self) -> Option<&[Point]> {
        if self.it_idx < self.streamlines.lengths.len() {
            let start = self.streamlines.offsets[self.it_idx];
            self.it_idx += 1;
            let end = self.streamlines.offsets[self.it_idx];
            Some(self.streamlines.data[start..end])
        }
        else {
            None
        }
    }
}

我使用了切片,因为我只想返回矢量的部分,然后我添加了终身,因为它是必需的,但是现在我有此错误 cannot infer an appropriate lifetime for lifetime parameter in generic type due to conflicting requirements

实际上,我实际上不知道我正在用该死的<'a>

由于要求相互冲突,无法推断通用类型中寿命参数的适当寿命

那是因为您无法正确实现Iterator并具有类似的东西:

impl<'a> Iterator for StreamlinesIterator<'a> {
    type Item = &'a [Point];
    fn next(&mut self) -> Option<&[Point]> { /* ... */ }
    // ...
}

由于寿命推断,这等效于:

impl<'a> Iterator for StreamlinesIterator<'a> {
    type Item = &'a [Point];
    fn next<'b>(&'b mut self) -> Option<&'b [Point]> { /* ... */ }
    // ...
}

这是试图返回只要迭代器就无法做的参考文献。

如果您正确实现了Iterator,则有效:

impl<'a> Iterator for StreamlinesIterator<'a> {
    type Item = &'a [Point];
    fn next(&mut self) -> Option<&'a [Point]> { /* ... */ }
    // Even better:   
    fn next(&mut self) -> Option<Self::Item> { /* ... */ }
    // ...
}

我实际上不知道我在用该死的<'a>

您应该返回并重新阅读 Rust编程语言,第二版。当您有特定的问题时,堆栈溢出,IRC,用户的论坛都将在等待。

最新更新