関連型

関連型を使用すると、コンテナ型の中の要素をトレイトの中に 出力型 として書くことで、全体の可読性を上げることができます。トレイトを定義する際の構文は以下のようになります。

#![allow(unused)] fn main() { // `A` and `B` are defined in the trait via the `type` keyword. // (Note: `type` in this context is different from `type` when used for // aliases). // `A`と`B`は`type`キーワードを用いてトレイト内で宣言されている。 // (注意: この文脈で使用する`type`は型エイリアスを宣言する際の`type`とは // 異なることに注意しましょう。) trait Contains { type A; type B; // Updated syntax to refer to these new types generically. // これらの新しい型をジェネリックに使用するために、構文が // アップデートされています。 fn contains(&self, _: &Self::A, _: &Self::B) -> bool; } }

Containsトレイトを使用する関数において、ABを明示する必要がなくなっていることに注目しましょう。

// Without using associated types // 関連型を使用しない場合 fn difference<A, B, C>(container: &C) -> i32 where C: Contains<A, B> { ... } // Using associated types // 使用する場合 fn difference<C: Contains>(container: &C) -> i32 { ... }

前セクションの例を関連型を使用して書きなおしてみましょう。

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX