关联类型

使用“关联类型”可以增强代码的可读性,其方式是移动内部类型到一个 trait 作为output(输出)类型。这个 trait 的定义的语法如下:

  1. // `A` 和 `B` 在 trait 里面通过`type` 关键字来定义。
  2. // (注意:此处的 `type` 不同于用作别名时的 `type`)。
  3. trait Contains {
  4. type A;
  5. type B;
  6. // 通常提供新语法来表示这些新的类型。
  7. // (原文:Updated syntax to refer to these new types generically.)
  8. fn contains(&self, &Self::A, &Self::B) -> bool;
  9. }

注意到上面函数用到了 Contains trait,再也不需要表达 AB

  1. // 不使用关联类型
  2. fn difference<A, B, C>(container: &C) -> i32 where
  3. C: Contains<A, B> { ... }
  4. // 使用关联类型
  5. fn difference<C: Contains>(container: &C) -> i32 { ... }

让我们使用关联类型来重写上一小节的例子:

  1. struct Container(i32, i32);
  2. // 这个 trait 检查 2 个项是否存到 Container(容器)中。
  3. // 还会获得第一个值或最后一个值。
  4. trait Contains {
  5. // 在这里定义可以被方法利用的泛型类型。
  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. // 指出 `A` 和 `B` 是什么类型。如果 `input`(输入)类型
  14. // 为 `Container(i32, i32)`,那么 `output`(输出)类型
  15. // 会被确定为 `i32` 和 `i32`。
  16. type A = i32;
  17. type B = i32;
  18. // `&Self::A` 和 `&Self::B` 在这里也是有效的。
  19. fn contains(&self, number_1: &i32, number_2: &i32) -> bool {
  20. (&self.0 == number_1) && (&self.1 == number_2)
  21. }
  22. // 得到第一个数字。
  23. fn first(&self) -> i32 { self.0 }
  24. // 得到最后一个数字。
  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. }