简体   繁体   English

关联类型的生命周期

[英]self lifetime on associated type

Full Rust example here: https://play.rust-lang.org/?gist=0778e8d120dd5e5aa7019bc097be392b&version=stable 完整的Rust示例在这里: https : //play.rust-lang.org/? gist = 0778e8d120dd5e5aa7019bc097be392b & version =stable

The general idea is to implement a generic split iterator that will yield iterators for each run of values that are split by the specified separator. 总体思路是实现一个通用的拆分迭代器,该迭代器将为由指定分隔符拆分的每次值运行生成迭代器。 So for [1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9],split(0) you would get [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 因此,对于[1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9],split(0)您将得到[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

For this code: 对于此代码:

impl<'a, I, F> Iterator for Split<I, F>
    where I: Iterator,
          F: PartialEq<I::Item>,
{
    type Item = SplitSection<'a, I, F>;
    fn next(&'a mut self) -> Option<Self::Item> {
        self.iter.peek().map(|_| 
        SplitSection {
            exhausted: false,
            iter: self,
        })
    }
}

I'm receiving the following error: 我收到以下错误:

error[E0207]: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates
  --> src/main.rs:22:6
   |
22 | impl<'a, I, F> Iterator for Split<I, F>
   |      ^^ unconstrained lifetime parameter

Is there a way to "constrain" the lifetime parameter, or refactor it somehow so that the associated type (Item) gets returned with a lifetime that will tie it back to next()? 有没有一种方法可以“约束”生命周期参数,或者以某种方式对其进行重构,以使关联的类型(Item)返回具有生命周期的生命周期,并将其绑定到next()?

Basically, since each SplitSection is using the iterator owned by Split, I want to make sure that two SplitSections are not iterated over at once. 基本上,由于每个SplitSection都使用Split拥有的迭代器,因此我想确保两个SplitSections不会一次迭代。

Thanks! 谢谢!

Sadly, this is currently not possible in Rust when implementing Iterator trait - it is not allowed to modify lifetime relations compared to original trait definition of the method. 遗憾的是,当前在Rust中实现Iterator特征时,这是不可能的-与该方法的原始特征定义相比,不允许修改生命周期关系。

Good news are that recently merged generic associated type RFC will provide a language feature to do so, when implemented in the compiler. 好消息是,当在编译器中实现时,最近合并的通用关联类型RFC将提供一种语言功能。 It will probably take some time though. 不过,可能需要一些时间。

I have tried to implement similar function myself recently and most simple approach I have found with existing stable compiler was to require Clone + Iterator , iterating split chunks separately from "host" iterator ( https://gitlab.com/mihails.strasuns/example-iterators-calendar/blob/master/src/split_adaptor.rs ) 我最近尝试自己实现类似的功能,而我发现与现有稳定编译器最简单的方法是要求Clone + Iterator ,与“主机”迭代器分开迭代拆分块( https://gitlab.com/mihails.strasuns/example -iterators-calendar / blob / master / src / split_adaptor.rs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM