关联类型
使用“关联类型”可以增强代码的可读性,其方式是移动内部类型到一个 trait 作为output(输出)类型。这个 trait 的定义的语法如下:
1. // `A` 和 `B` 在 trait 里面通过`type` 关键字来定义。
2. // (注意:此处的 `type` 不同于用作别名时的 `type`)。
3. trait Contains {
4. type A;
5. type B;
7. // 通常提供新语法来表示这些新的类型。
8. // (原文:Updated syntax to refer to these new types generically.)
9. fn contains(&self, &Self::A, &Self::B) -> bool;
10. }
注意到上面函数用到了 Contains trait,再也不需要表达 A 或 B:
1. // 不使用关联类型
2. fn difference<A, B, C>(container: &C) -> i32 where
3. C: Contains<A, B> { ... }
5. // 使用关联类型
6. fn difference<C: Contains>(container: &C) -> i32 { ... }
让我们使用关联类型来重写上一小节的例子:
1. struct Container(i32, i32);
3. // 这个 trait 检查 2 个项是否存到 Container(容器)中。
4. // 还会获得第一个值或最后一个值。
5. trait Contains {
6. // 在这里定义可以被方法利用的泛型类型。
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. // 指出 `A` 和 `B` 是什么类型。如果 `input`(输入)类型
17. // 为 `Container(i32, i32)`,那么 `output`(输出)类型
18. // 会被确定为 `i32` 和 `i32`。
19. type A = i32;
20. type B = i32;
22. // `&Self::A` 和 `&Self::B` 在这里也是有效的。
23. fn contains(&self, number_1: &i32, number_2: &i32) -> bool {
24. (&self.0 == number_1) && (&self.1 == number_2)
25. }
27. // 得到第一个数字。
28. fn first(&self) -> i32 { self.0 }
30. // 得到最后一个数字。
31. fn last(&self) -> i32 { self.1 }
32. }
34. fn difference<C: Contains>(container: &C) -> i32 {
35. container.last() - container.first()
36. }
38. fn main() {
39. let number_1 = 3;
40. let number_2 = 10;
42. let container = Container(number_1, number_2);
44. println!("Does container contain {} and {}: {}",
45. &number_1, &number_2,
46. container.contains(&number_1, &number_2));
47. println!("First number: {}", container.first());
48. println!("Last number: {}", container.last());
50. println!("The difference is: {}", difference(&container));
51. }
