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;
8. // Updated syntax to refer to these new types generically.
9. fn contains(&self, &Self::A, &Self::B) -> bool;
10. }
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> { ... }
5. // Using associated types
6. fn difference<C: Contains>(container: &C) -> i32 { ... }
Let’s rewrite the example from the previous section using associated types:
1. struct Container(i32, i32);
3. // A trait which checks if 2 items are stored inside of container.
4. // Also retrieves first or last value.
5. trait Contains {
6. // Define generic types here which methods will be able to utilize.
7. type A;
8. type B;
10. fn contains(&self, &Self::A, &Self::B) -> bool;
11. fn first(&self) -> i32;
12. fn last(&self) -> i32;
13. }
15. impl Contains for Container {
16. // Specify what types `A` and `B` are. If the `input` type
17. // is `Container(i32, i32)`, the `output` types are determined
18. // as `i32` and `i32`.
19. type A = i32;
20. type B = i32;
22. // `&Self::A` and `&Self::B` are also valid here.
23. fn contains(&self, number_1: &i32, number_2: &i32) -> bool {
24. (&self.0 == number_1) && (&self.1 == number_2)
25. }
26. // Grab the first number.
27. fn first(&self) -> i32 { self.0 }
29. // Grab the last number.
30. fn last(&self) -> i32 { self.1 }
31. }
33. fn difference<C: Contains>(container: &C) -> i32 {
34. container.last() - container.first()
35. }
37. fn main() {
38. let number_1 = 3;
39. let number_2 = 10;
41. let container = Container(number_1, number_2);
43. println!("Does container contain {} and {}: {}",
44. &number_1, &number_2,
45. container.contains(&number_1, &number_2));
46. println!("First number: {}", container.first());
47. println!("Last number: {}", container.last());
49. println!("The difference is: {}", difference(&container));
50. }
