rust / intermediate
Snippet
Associated Types in Traits
Associated types allow you to declare placeholder types within traits that implementing types must specify. Unlike generic type parameters (Container<T>), associated types (Container::Item) are resolved at implementation time, enabling clearer trait signatures and supporting better type inference in complex trait hierarchies.
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
41
42
43
44
45
46
47
trait Container {type Item;fn get(&self, index: usize) -> Option<&Self::Item>;fn len(&self) -> usize;fn is_empty(&self) -> bool {self.len() == 0}}struct Stack<T> {items: Vec<T>,}impl<T> Container for Stack<T> {type Item = T;fn get(&self, index: usize) -> Option<&Self::Item> {self.items.get(index)}fn len(&self) -> usize {self.items.len()}}fn find_first<C: Container>(container: &C) -> Option<&C::Item>whereC::Item: Clone,{if container.is_empty() {None} else {container.get(0)}}fn main() {let stack: Stack<i32> = Stack { items: vec![10, 20, 30] };println!("Stack length: {}", stack.len());println!("First item: {:?}", stack.get(0));println!("Is empty: {}", stack.is_empty());if let Some(item) = find_first(&stack) {println!("Found first item: {}", item);}}
Breakdown
1
type Item;
Associated type declaration in trait - implementing types must provide a concrete type
2
type Item = T;
Implementing associated type - Stack uses its generic T as the Item type
3
C::Item
Referencing associated type in where clause - used for bounds on the associated type
4
where C::Item: Clone
Constraining the associated type - only containers with Clone items can use find_first