Rust, typed: associated types

What is an associated type?

An associated type is defined as a type inside of a trait declaration. Associated types can be constrasted with generic type parameters, the difference being that associated types are not parameters, but rather items in the trait declaration.

How is an associated type declared?

To use associated types in a trait declaration just place a type definition inside the trait body. Associated types can imply other traits. To declare such a subtype relation, follow the associated type declaration with a colon and the implied types.

To implement a trait with an associated type, the associated type must be assigned a concrete type. This gives a little more flexibility as to how a trait type is generalized and assigned when compared to a direct type parameter.

trait Assoc {
   type L: std::fmt::Display;
   type R: std::fmt::Display;
   fn left(&self) -> &Self::L;
   fn right(&self) -> &Self::R;
}

struct Pair(u64,u64);
impl Assoc for Pair {
   type L = u64;
   type R = u64;
   fn left(&self) -> &Self::L { &self.0 }
   fn right(&self) -> &Self::R { &self.1 }
}

fn main() {
   println!("left: {}", Pair(2,3).left());
}