CodeBlanks Logo Icon CodeBlanks

Associated type

Define an associated type in a trait.

Associated types

An associated type is a type placeholder named inside a trait, decided once by each implementation. Iterator::Item is the best-known example:

trait Kap {
    type Oge;
    fn al(&self, i: usize) -> Option<&Self::Oge>;
}

struct Liste(Vec<String>);

impl Kap for Liste {
    type Oge = String;
    fn al(&self, i: usize) -> Option<&String> {
        self.0.get(i)
    }
}

The difference from a generic parameter (trait Kap<T>): a type can implement the trait only once, and the type doesn't need to be written when using it.

Bounding with an associated type

In generic code the associated type is reached as T::Oge and can be bounded:

fn ilk_yaz<K>(k: &K)
where
    K: Kap,
    K::Oge: std::fmt::Debug,
{
    println!("{:?}", k.al(0));
}

// a bound requiring a specific element type:
fn metinler<K: Kap<Oge = String>>(k: &K) { .. }

Practice Container trait

Write the Kap trait above and the Liste implementation. Print the results of al(1) and al(5) for Liste(vec!["a".into(), "b".into()]) with {:?}, separated by a space.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
trait Kap {
    type Oge;
    fn al(&self, i: usize) -> Option<&Self::Oge>;
}

struct Liste(Vec<String>);

impl Kap for Liste {
    type Oge = String;
    fn al(&self, i: usize) -> Option<&String> {
        self.0.get(i)
    }
}

fn main() {
    let l = Liste(vec!["a".into(), "b".into()]);
    println!("{:?} {:?}", l.al(1), l.al(5));
}

Expected output

Some("b") None

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is a generic parameter chosen over an associated type?

  • Always
  • Never
  • For performance
  • When it makes sense for a type to implement the trait for several types (like From<T>) Correct answer

Explanation: String implements both From<&str> and From<char>; an iterator has a single Item type.

2 Set the associated type

Question
impl Kap for Liste {
    type ____ = String;
    fn al(&self, i: usize) -> Option<&String> { self.0.get(i) }
}
Answer
impl Kap for Liste {
    type Oge = String;
    fn al(&self, i: usize) -> Option<&String> { self.0.get(i) }
}

Explanation: The implementation sets the associated type declared in the trait.

3 Syntax and meaning

Term Meaning
type Oge; Declaration
type Oge = String; Set in the impl
K::Oge Access in generic code
Kap<Oge = String> Equality bound

All lessons in Advanced