RRust By Example
advancedTraits

Associated Types

Define associated types in traits for cleaner generic code.

Associated Types

Define associated types in traits for cleaner generic code.

Difficulty

Advanced

Code

rust
trait Container {
    type Item;
    fn get(&self) -> Option<&Self::Item>;
    fn set(&mut self, item: Self::Item);
}

struct Single<T> {
    value: Option<T>,
}

impl<T> Container for Single<T> {
    type Item = T;

    fn get(&self) -> Option<&T> {
        self.value.as_ref()
    }

    fn set(&mut self, item: T) {
        self.value = Some(item);
    }
}

fn main() {
    let mut s = Single { value: None };
    s.set(42);
    println!("value: {:?}", s.get());
}

Explanation

Associated types in traits define placeholder types.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the traits category to build a complete understanding of this topic.

More Traits Examples