通过把容器内部的类型放到 trait
中作为输出类型,使用 “关联类型” 增加了代码
的可读性。这样的 trait
的定义语法如下:
#![allow(unused)]
fn main() {
trait Contains {
type A;
type B;
fn contains(&self, _: &Self::A, _: &Self::B) -> bool;
}
}
注意使用了 Contains
trait
的函数就不需要写出 A
或 B
了:
fn difference<A, B, C>(container: &C) -> i32 where
C: Contains<A, B> { ... }
fn difference<C: Contains>(container: &C) -> i32 { ... }
让我们使用关联类型来重写上一小节的例子:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX