共享类型

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);

6. trait Multiply {
7. type Output;
8. fn multiply(&self, other: &Self) -> Self::Output;
9. }

11. impl Multiply for Meters {
12. type Output = MetersSquared;
13. fn multiply(&self, other: &Self) -> Self::Output {
14. MetersSquared(self.0 * other.0)
15. }
16. }

18. fn main() {
19. println!("{:?}", Meters(10).multiply(&Meters(20)));
20. }
  • 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.