簡體   English   中英

從迭代器返回切片時無法推斷適當的生命周期

[英]Cannot infer an appropriate lifetime when returning a slice from an iterator

我有一個帶有簡單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!("")
}

我發現了如何為一個簡單的結構實現Iterator和IntoIterator? 並開始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 ,現在我有此錯誤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),用戶論壇時,都將處於等待狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM