【问题标题】:self lifetime on associated type关联类型的自我生命周期
【发布时间】:2018-02-18 01:30:17
【问题描述】:

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

一般的想法是实现一个通用的拆分迭代器,它将为每个由指定分隔符拆分的值生成迭代器。所以对于[1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9],split(0),你会得到[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

对于此代码:

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,
        })
    }
}

我收到以下错误:

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

有没有办法“约束”生命周期参数,或者以某种方式对其进行重构,以便关联类型 (Item) 的返回生命周期将其绑定回 next()?

基本上,由于每个 SplitSection 都使用 Split 拥有的迭代器,所以我想确保两个 SplitSection 不会一次迭代。

谢谢!

【问题讨论】:

    标签: rust


    【解决方案1】:

    遗憾的是,在实现 Iterator 特征时,目前在 Rust 中这是不可能的 - 与方法的原始特征定义相比,不允许修改生命周期关系。

    好消息是,最近合并的generic associated type RFC 将在编译器中实现时提供语言功能来执行此操作。不过这可能需要一些时间。

    我最近尝试自己实现类似的功能,我发现使用现有稳定编译器的最简单方法是要求 Clone + Iterator,将拆分块与“主机”迭代器分开迭代 (https://gitlab.com/mihails.strasuns/example-iterators-calendar/blob/master/src/split_adaptor.rs)

    【讨论】:

      猜你喜欢
      • 2023-02-10
      • 2017-12-29
      • 2016-02-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多