我有一个 Vec<Point>
用一个简单的 struct Point {x: f32, y: f32, z: f32}
.我的向量在 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!("")
}
我找到了 How to implement Iterator and IntoIterator for a simple struct?并开始 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>
做什么.
最佳答案
cannot infer an appropriate lifetime for lifetime parameter in generic type due to conflicting requirements
那是因为你没有正确实现 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]> { /* ... */ }
// ...
}
这试图返回一个与迭代器一样长的引用,which you cannot do .
如果您正确实现 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> { /* ... */ }
// ...
}
I don't actually know what I'm doing with the damn
<'a>
.
你应该回去重新阅读The Rust Programming Language, second edition .当您有具体问题时,Stack Overflow、IRC、用户论坛都将等待。
关于rust - 从迭代器返回切片时无法推断出合适的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46529282/