gpt4 book ai didi

iterator - 试图实现迭代器 : cannot infer an appropriate lifetime due to conflicting requirements

转载 作者:行者123 更新时间:2023-11-29 08:06:20 25 4
gpt4 key购买 nike

我正在尝试在我自己的结构上实现一个迭代器。我的一般方法是在第一次调用 next 时生成并存储一个迭代器,然后在每次需要值时调用这个迭代器。

我的最小失败示例 looks like this ,它的核心是:

    if !self.vals.is_some() {
self.vals = Some(Box::new({
self.display.chars().filter(|&i| i == self.look_for)
}) as Box<std::iter::Iterator<Item = _>>);
}

我的代码无法编译,生成以下消息:

help: consider using an explicit lifetime parameter as shown: fn next(self: &'a mut Self) -> Option<<Self>::Item>

遵循建议没有帮助(只会导致更多编译错误,表明我的实现与 Iterator 特征定义不兼容。

如果您能帮助我了解出了什么问题以及我该如何解决它,我将不胜感激。

最佳答案

问题是你传递给filter的闭包需要借用self,但是you can't store a reference to self in the struct itself .

在这种情况下,我们可以通过在闭包中存储值的副本来解决这个问题。这分两步完成:

  1. self.look_for 赋值给局部变量,并在闭包中使用局部变量。这样,闭包就不会绑定(bind)到 self
  2. move 添加到闭包中。因此,闭包将按值捕获局部变量。

这是最终代码:

impl<'a> Iterator for StatefulCounter<'a> {
type Item = bool;
fn next(&mut self) -> Option<Self::Item> {
if !self.vals.is_some() {
let look_for = self.look_for;
self.vals = Some(Box::new({
self.display.chars().filter(move |&i| i == look_for)
}));
}

if let &Some(v) = &self.vals.as_mut().unwrap().next() {
Some(expensive(v))
} else {
None
}
}
}

Box 上的显式转换不是必需的,所以我删除了它。

关于iterator - 试图实现迭代器 : cannot infer an appropriate lifetime due to conflicting requirements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41786651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com