简体   繁体   English

为什么需要定义特征来定义外部类型的实现?

[英]Why do I need to define a trait to define an implementation on an external type?

The std::iter library has an AdditiveIter trait which only ever has a single impl : std::iter库具有AdditiveIter特性 ,该特性仅具有一个impl

pub trait AdditiveIterator<A> {
  fn sum(&mut self) -> A;
}

impl<A: Add<A, A> + Zero, T: Iterator<A>> AdditiveIterator<A> for T {
  fn sum(&mut self) -> A {
      let zero: A = Zero::zero();
      self.fold(zero, |s, x| s + x)
  }
}

This trait exists so that we can write foo.iter().sum() . 存在此特征以便我们可以编写foo.iter().sum() If we were happy with writing sum(foo.iter()) instead, then the above code could be written more simply as: 如果我们对编写sum(foo.iter())感到满意,那么上面的代码可以更简单地写为:

fn sum<A: Add<A, A> + Zero, T: Iterator<A>>(iter: &mut T) -> A {
    let zero: A = Zero::zero();
    iter.fold(zero, |s, x| s + x)
}

Is there a way to get the best of both? 有没有办法做到两者兼得? Can I write sum so that: 我可以写出sum以便:

  • I can use foo.iter().sum() syntax; 我可以使用foo.iter().sum()语法; and

  • I don't have to duplicate the fn sum(&mut self) -> A type signature? 我不必重复fn sum(&mut self) -> A类型签名?

Iterator is not a type, it's actually a trait. Iterator不是类型,实际上是特征。 If it was a type then this would be possible, something like: 如果是一种类型,那么这将是可能的,例如:

impl<A: Add<A, A> + Zero> Iterator<A> {
  fn sum(&mut self) -> A {
      let zero: A = Zero::zero();
      self.fold(zero, |s, x| s + x)
  }
}

If we could implement methods on a generic type we could do: 如果我们可以在通用类型上实现方法,则可以执行以下操作:

impl<A: Add<A, A> + Zero, T: Iterator<A>> T {
  fn sum(&mut self) -> A {
      let zero: A = Zero::zero();
      self.fold(zero, |s, x| s + x)
  }
}

But the compiler doesn't like that, and forces us to define a new trait. 但是编译器不喜欢这样,迫使我们定义一个新的特征。

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

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