Rust中这种奇怪的递归类型错误是怎么回事?

时间:2018-11-21 04:31:03

标签: types reference rust type-inference

我有一个名为Join的可迭代结构:

use std::iter::Peekable;

#[derive(Debug)]
pub struct Join<T, S> {
    container: T,
    separator: S,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JoinItem<T, S> {
    Element(T),
    Separator(S),
}

pub struct JoinIter<Iter: Iterator, Sep> {
    iter: Peekable<Iter>,
    sep: Sep,
    next_sep: bool,
}

impl<Iter: Iterator, Sep> JoinIter<Iter, Sep> {
    fn new(iter: Iter, sep: Sep) -> Self {
        JoinIter {
            iter: iter.peekable(),
            sep,
            next_sep: false,
        }
    }
}

impl<I: Iterator, S: Clone> Iterator for JoinIter<I, S> {
    type Item = JoinItem<I::Item, S>;

    /// Advance to the next item in the Join. This will either be the next
    /// element in the underlying iterator, or a clone of the separator.
    fn next(&mut self) -> Option<Self::Item> {
        let sep = &self.sep;
        let next_sep = &mut self.next_sep;

        if *next_sep {
            self.iter.peek().map(|_| {
                *next_sep = false;
                JoinItem::Separator(sep.clone())
            })
        } else {
            self.iter.next().map(|element| {
                *next_sep = true;
                JoinItem::Element(element)
            })
        }
    }
}

Join的引用实现了IntoIterator

impl<'a, T, S> IntoIterator for &'a Join<T, S>
where
    &'a T: IntoIterator,
{
    type IntoIter = JoinIter<<&'a T as IntoIterator>::IntoIter, &'a S>;
    type Item = JoinItem<<&'a T as IntoIterator>::Item, &'a S>;

    fn into_iter(self) -> Self::IntoIter {
        JoinIter::new(self.container.into_iter(), &self.separator)
    }
}

这将编译并通过使用测试。

我在iter结构上定义了一个Join方法:

impl<T, S> Join<T, S>
where
    for<'a> &'a T: IntoIterator,
{
    pub fn iter(&self) -> JoinIter<<&T as IntoIterator>::IntoIter, &S> {
        self.into_iter()
    }
}

这可以很好地编译,但是当我实际尝试使用它时:

fn main() {
    // Create a join struct
    let join = Join {
        container: vec![1, 2, 3],
        separator: ", ",
    };

    // This works fine
    let mut good_ref_iter = (&join).into_iter();
    assert_eq!(good_ref_iter.next(), Some(JoinItem::Element(&1)));
    assert_eq!(good_ref_iter.next(), Some(JoinItem::Separator(&", ")));
    assert_eq!(good_ref_iter.next(), Some(JoinItem::Element(&2)));
    assert_eq!(good_ref_iter.next(), Some(JoinItem::Separator(&", ")));
    assert_eq!(good_ref_iter.next(), Some(JoinItem::Element(&3)));
    assert_eq!(good_ref_iter.next(), None);

    // This line fails to compile; comment out this section and it all works
    let bad_ref_iter = join.iter();
    assert_eq!(bad_ref_iter.next(), Some(JoinItem::Element(&1)));
    assert_eq!(bad_ref_iter.next(), Some(JoinItem::Separator(&", ")));
    assert_eq!(bad_ref_iter.next(), Some(JoinItem::Element(&2)));
    assert_eq!(bad_ref_iter.next(), Some(JoinItem::Separator(&", ")));
    assert_eq!(bad_ref_iter.next(), Some(JoinItem::Element(&3)));
    assert_eq!(bad_ref_iter.next(), None);
}

我遇到某种奇怪的类型递归错误:

error[E0275]: overflow evaluating the requirement `&_: std::marker::Sized`
   --> src/join.rs:288:29
    |
 96 |         let mut iter = join.iter();
    |                             ^^^^
    |
    = help: consider adding a `#![recursion_limit="128"]` attribute to your crate
    = note: required because of the requirements on the impl of `std::iter::IntoIterator` for `&_`
    = note: required because of the requirements on the impl of `std::iter::IntoIterator` for `&join::Join<_, _>`
    = note: required because of the requirements on the impl of `std::iter::IntoIterator` for `&join::Join<join::Join<_, _>, _>`
    = note: required because of the requirements on the impl of `std::iter::IntoIterator` for `&join::Join<join::Join<join::Join<_, _>, _>, _>`
    = note: required because of the requirements on the impl of `std::iter::IntoIterator` for `&join::Join<join::Join<join::Join<join::Join<_, _>, _>, _>, _>`
    = note: required because of the requirements on the impl of `std::iter::IntoIterator` for `&join::Join<join::Join<join::Join<join::Join<join::Join<_, _>, _>, _>, _>, _>`
    = note: required because of the requirements on the impl of `std::iter::IntoIterator` for `&join::Join<join::Join<join::Join<join::Join<join::Join<join::Join<_, _>, _>, _>, _>, _>, _>`
...

(我在...中重新编写了约100行递归类型错误)

据我所知,它似乎正在尝试主动评估&Join<_, _>是否实现IntoIterator,这需要检查&Join<Join<_, _>, _>是否实现IntoIterator,等等,直到永远。我无法弄清为什么它认为必须这样做,因为我的实际类型完全符合Join<Vec<{integer}, &'static str>的条件。我尝试过的一些事情:

  • 将特征绑定从impl标头移到iter函数中,如下所示:

    fn iter(&'a self) -> JoinIter<<&'a T as IntoIterator>::IntoIter, &'a S>
    where &'a T: IntoIterator
    

    结果相同。

  • 用基础表达式self.into_iter()替换JoinIter::new(self.container.into_iter(), self.separator),希望将self.into_iter()(&self).into_iter()区分开来是很困难的。我已经尝试了以下所有模式:

    • fn iter(&self) -> ... { self.into_iter() }
    • fn iter(&self) -> ... { (&self).into_iter() }
    • fn iter(&self) -> ... { JoinIter::new(self.container.into_iter(), &self.separator) }
    • fn iter(&self) -> ... { JoinIter::new((&self.container).into_iter(), &self.separator) }
  • 说到此,用self.iter()替换对(&self).into_iter()的调用可以解决问题,但不能用(&self).iter()替换。

即使(&join).into_iter()只是简单地调用join.iter(),为什么iter()仍然有效,而self.into_iter()却无效?

Rust Playground

中也提供了具有相同代码的完整示例。

有关Join的更多信息,请参见我的较老Stack Overflow question和实际的source code

1 个答案:

答案 0 :(得分:2)

似乎编译器无法解决iter()返回类型JoinIter<<&T as IntoIterator>::IntoIter, &S>所需的特征要求。

我从rustc --explain E0275错误说明中得到了一个提示:

  

当递归特征要求溢出时,会发生此错误   在评估之前。通常,这意味着存在无限   递归以解决某些类型边界。

我不知道铁锈的推断过程的细节,我想以下情况正在发生。

签署此签名:

fn iter(&self) -> JoinIter<<&T as IntoIterator>::IntoIter, &S>

编译器尝试从以下方法推断返回类型:

JoinIter<<&T as IntoIterator>::IntoIter, &S>

但是<&T as IntoIterator>::IntoIter是根据&'a Join隐含推论得出的:

impl<'a, T, S> IntoIterator for &'a Join<T, S>
    where &'a T: IntoIterator
{
    type IntoIter = JoinIter<<&'a T as IntoIterator>::IntoIter, &'a S>;
    type Item = JoinItem<<&'a T as IntoIterator>::Item, &'a S>;

    fn into_iter(self) -> Self::IntoIter {
        JoinIter::new(self.container.into_iter(), &self.separator)
    }
}

IntoIter仍然是JoinIter<<&'a T as IntoIterator>::IntoIter, &'a S>,具有IntoIter等,因此是无限的。

使其编译的一种方法是帮助编译器使用turbofish

let mut bad_ref_iter = Join::<Vec<i32>, &str>::iter(&join);

代替:

let bad_ref_iter = join.iter();

更新

该行:

type IntoIter = JoinIter<<&'a T as IntoIterator>::IntoIter, &'a S>;    

之所以生成递归,是因为Rust会在特征被定义而不是使用时检查特征是否有效。

有关更多详细信息和工作进度的指针,请参见this post 归一化,可以解决这个问题。