rust / intermediate
Snippet
Associated Types in Traits
Associated types define placeholder types within traits that implementing types must specify. Unlike generic trait parameters, associated types ensure only one implementation exists per type, preventing ambiguous method calls. They're ideal when each implementer needs exactly one concrete type for the relationship—this enables cleaner method signatures and allows the compiler to infer types. The where clause further constrains that the Item type must implement Debug.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
trait Graph<N, E> {fn edges_between(&self, n1: &N, n2: &N) -> Option<&E>;}trait Container {type Item;fn add(&mut self, item: Self::Item);fn get(&self, index: usize) -> Option<&Self::Item>;}struct Stack<T> {items: Vec<T>,}impl<T> Container for Stack<T> {type Item = T;fn add(&mut self, item: T) { self.items.push(item); }fn get(&self, index: usize) -> Option<&T> { self.items.get(index) }}trait Serializable {type Output: std::fmt::Display;fn serialize(&self) -> Self::Output;}impl Serializable for i32 {type Output = String;fn serialize(&self) -> String { format!("i32:{}", self) }}impl Serializable for String {type Output = String;fn serialize(&self) -> String { format!("str:{}", self) }}fn process<C: Container>(container: &C) -> usizewhere C::Item: std::fmt::Debug {container.get(0).map(|i| println!("First: {:?}", i));42}
Breakdown
1
type Item;
Placeholder type declared in trait definition
2
type Item = T;
Concrete type provided in implementation
3
Self::Item
Reference to associated type in trait methods
4
C::Item: Debug
Where clause bounds associated type indirectly
5
Container<Item = T>
Full qualification of associated type binding