如何为特征提供IntoIterator的默认实现?

时间:2019-05-30 07:43:35

标签: rust traits

我具有以下特征和一个迭代器:

pub trait Stack<'a> {
    type Item;

    fn empty() -> Self;
    fn is_empty(&self) -> bool;
    fn cons(&'a self, val: &'a Self::Item) -> Self;
    fn head(&self) -> &Self::Item;
    fn tail(&self) -> &Self;
}

pub struct StackIter<'a, TStack: Stack<'a>> {
    stack: &'a TStack,
}

impl<'a, TStack: Stack<'a>> Iterator for StackIter<'a, TStack> {
    type Item = &'a TStack::Item;
    fn next(&mut self) -> Option<Self::Item> {
        if self.stack.is_empty() {
            Option::None
        } else {
            let val = self.stack.head();
            self.stack = self.stack.tail();
            Option::Some(val)
        }
    }
}

我想为IntoIterator特性定义Stack的默认实现,所以我尝试了以下方法:

pub trait Stack<'a>: IntoIterator {
    fn into_iter(self) -> Self::IntoIter {
        /* ... */
    }
}

这将无法正常工作,因为我们无法为类型IntoIterator::IntoIter定义默认值。

我尝试提供Stack之外的实现:

impl<'a, TStack: Stack<'a>> IntoIterator for &'a TStack {
    type Item = &'a TStack::Item;
    type IntoIter = StackIter<'a, TStack>;
    fn into_iter(self) -> Self::IntoIter {
        StackIter { stack: self }
    }
}

但是随后出现以下错误:

error[E0119]: conflicting implementations of trait `std::iter::IntoIterator` for type `&_`:
  --> src/lib.rs:28:1
   |
28 | impl<'a, TStack: Stack<'a>> IntoIterator for &'a TStack {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: conflicting implementation in crate `core`:
           - impl<I> std::iter::IntoIterator for I
             where I: std::iter::Iterator;
   = note: downstream crates may implement trait `std::iter::Iterator` for type `&_`

error[E0210]: type parameter `TStack` must be used as the type parameter for some local type (e.g., `MyStruct<TStack>`)
  --> src/lib.rs:28:1
   |
28 | impl<'a, TStack: Stack<'a>> IntoIterator for &'a TStack {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type parameter `TStack` must be used as the type parameter for some local type
   |
   = note: only traits defined in the current crate can be implemented for a type parameter

0 个答案:

没有答案