共享类型

Associated types are placeholder types which are supplied by the trait implementation.

  1. #[derive(Debug)]
  2. struct Meters(i32);
  3. #[derive(Debug)]
  4. struct MetersSquared(i32);
  5. trait Multiply {
  6. type Output;
  7. fn multiply(&self, other: &Self) -> Self::Output;
  8. }
  9. impl Multiply for Meters {
  10. type Output = MetersSquared;
  11. fn multiply(&self, other: &Self) -> Self::Output {
  12. MetersSquared(self.0 * other.0)
  13. }
  14. }
  15. fn main() {
  16. println!("{:?}", Meters(10).multiply(&Meters(20)));
  17. }
  • Associated types are sometimes also called “output types”. The key observation is that the implementer, not the caller, chooses this type.

  • Many standard library traits have associated types, including arithmetic operators and Iterator.