【发布时间】:2015-01-07 18:23:43
【问题描述】:
我天真地尝试这样做:
struct Foo<'a, S: Send, T:Send> {
next_:Box<Fn<(&'a mut S,), Option<T>> + Send>,
state:S
}
impl<'a, S: Send, T: Send> Iterator<T> for Foo<'a, S, T> {
fn next(&mut self) -> Option<T> {
return self.next_.call((&mut self.state,));
}
}
要创建迭代器,我可以使用闭包轻松发送到任务。
但是,它会产生可怕的生命周期不匹配错误:
<anon>:8:33: 8:48 error: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
<anon>:8 return self.next_.call((&mut self.state,));
^~~~~~~~~~~~~~~
<anon>:7:5: 9:6 help: consider using an explicit lifetime parameter as shown: fn next(&'a mut self) -> Option<T>
<anon>:7 fn next(&mut self) -> Option<T> {
<anon>:8 return self.next_.call((&mut self.state,));
<anon>:9 }
error: aborting due to previous error
playpen: application terminated with error code 101
我不明白这个错误。
闭包应该接受一个生命周期为 'a 的参数,即结构的生命周期。
状态归结构所有,因此它的生命周期为 'a。
使用 next_.call((&mut self.state,)) 不会调用任务;它应该只在 call() 期间,据我所知应该是有效的。
所以这里的不匹配是在 next() 中 self 的生命周期和调用中的 'a 之间......但我不明白为什么它不会是 'a。
修复上述代码的正确方法是什么?
有没有更好的方法来做到这一点?
游戏围栏:http://is.gd/hyNi0S
【问题讨论】:
标签: rust