関連型
関連型は、トレイトの実装によって提供されるプレースホルダー型です。
// 著作権 2024 Google LLC // SPDX-License-Identifier: Apache-2.0 #[derive(Debug)] struct Meters(i32); #[derive(Debug)] struct MetersSquared(i32); trait Multiply { type Output; fn multiply(&self, other: &Self) -> Self::Output; } impl Multiply for Meters { type Output = MetersSquared; fn multiply(&self, other: &Self) -> Self::Output { MetersSquared(self.0 * other.0) } } fn main() { println!("{:?}", Meters(10).multiply(&Meters(20))); }
-
関連型は「出力型」と呼ばれることもあります。重要な点は、この型を選ぶのは呼び出し側ではなく実装側だということです。
-
標準ライブラリの多くのトレイトには、算術演算子トレイトや
Iteratorを含め、関連型があります。