Associated types

The use of “Associated types” improves the overall readability of code
by moving inner types locally into a trait as output types. Syntax
for the trait definition is as follows:

  1. // `A` and `B` are defined in the trait via the `type` keyword.
  2. // (Note: `type` in this context is different from `type` when used for
  3. // aliases).
  4. trait Contains {
  5. type A;
  6. type B;
  7. // Updated syntax to refer to these new types generically.
  8. fn contains(&self, &Self::A, &Self::B) -> bool;
  9. }

Note that functions that use the trait Contains are no longer required
to express A or B at all:

  1. // Without using associated types
  2. fn difference<A, B, C>(container: &C) -> i32 where
  3. C: Contains<A, B> { ... }
  4. // Using associated types
  5. fn difference<C: Contains>(container: &C) -> i32 { ... }

Let’s rewrite the example from the previous section using associated types:

  1. struct Container(i32, i32);
  2. // A trait which checks if 2 items are stored inside of container.
  3. // Also retrieves first or last value.
  4. trait Contains {
  5. // Define generic types here which methods will be able to utilize.
  6. type A;
  7. type B;
  8. fn contains(&self, &Self::A, &Self::B) -> bool;
  9. fn first(&self) -> i32;
  10. fn last(&self) -> i32;
  11. }
  12. impl Contains for Container {
  13. // Specify what types `A` and `B` are. If the `input` type
  14. // is `Container(i32, i32)`, the `output` types are determined
  15. // as `i32` and `i32`.
  16. type A = i32;
  17. type B = i32;
  18. // `&Self::A` and `&Self::B` are also valid here.
  19. fn contains(&self, number_1: &i32, number_2: &i32) -> bool {
  20. (&self.0 == number_1) && (&self.1 == number_2)
  21. }
  22. // Grab the first number.
  23. fn first(&self) -> i32 { self.0 }
  24. // Grab the last number.
  25. fn last(&self) -> i32 { self.1 }
  26. }
  27. fn difference<C: Contains>(container: &C) -> i32 {
  28. container.last() - container.first()
  29. }
  30. fn main() {
  31. let number_1 = 3;
  32. let number_2 = 10;
  33. let container = Container(number_1, number_2);
  34. println!("Does container contain {} and {}: {}",
  35. &number_1, &number_2,
  36. container.contains(&number_1, &number_2));
  37. println!("First number: {}", container.first());
  38. println!("Last number: {}", container.last());
  39. println!("The difference is: {}", difference(&container));
  40. }