我正在为多个结构实现 Iterator
特性并遇到了一些问题。为什么为 Rows
实现 Iterator
显示错误?
这是一个链接:link to playground
基本上为什么这不起作用?
struct Stripe<'a> {
cells: &'a [u32],
}
struct Rows<'a> {
foo: &'a Foo,
vec: Vec<u32>,
first: bool,
}
impl<'a> std::iter::Iterator for Rows<'a> {
type Item = Stripe<'a>;
fn next(&mut self) -> Option<Stripe<'a>> {
if self.first {
self.first = false;
Some(
Stripe {
cells: &self.vec[0..1],
}
)
} else {
None
}
}
}
最佳答案
Row
类型中的生存期'a
仅引用该类型的一个字段。您返回的引用与该生命周期无关。 Iterator
特性不允许您将生命周期返回到迭代器对象本身。这将需要向 next
函数添加新的生命周期。
我建议您创建一个 RowsIterator
类型并引用您的 Rows
对象并在其中处理特定于迭代器的内容:
struct Stripe<'a> {
cells: &'a [u32],
}
struct Rows {
vec: Vec<u32>,
}
struct RowsIter<'a> {
rows: &'a Rows,
first: bool,
}
impl<'a> std::iter::Iterator for RowsIter<'a> {
type Item = Stripe<'a>;
fn next(&mut self) -> Option<Stripe<'a>> {
if self.first {
self.first = false;
Some(
Stripe {
cells: &self.rows.vec[0..1],
}
)
} else {
None
}
}
}
playground 中的完整示例
关于iterator - 实现 Iterator 时的生命周期问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32145163/