capypad
0 day streak
rust / intermediate
Snippet

Associated Types in Trait Definitions

Associated types let you declare a placeholder type within a trait. Implementors of the trait specify the concrete type. This is different from generics—a Container<T> would let callers decide the type, but with associated types, each implementation fixes one type.

snippet.rs
rust
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;
}
 
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()
}
}
 
struct Matrix {
data: Vec<Vec<f64>>,
}
 
impl Container for Matrix {
type Item = Vec<f64>;
 
fn get(&self, index: usize) -> Option<&Self::Item> {
self.data.get(index)
}
 
fn len(&self) -> usize {
self.data.len()
}
}
 
fn main() {
let stack: Stack<i32> = Stack { items: vec![1, 2, 3] };
println!("Stack length: {}", stack.len());
println!("Stack item at 1: {:?}", stack.get(1));
 
let matrix = Matrix { data: vec![vec![1.0, 2.0], vec![3.0, 4.0]] };
println!("Matrix rows: {}", matrix.len());
println!("Matrix row at 0: {:?}", matrix.get(0));
}
Breakdown
1
type Item;
Placeholder type declared in trait; must be specified in impl
2
Self::Item
References the associated type from the implementing type
3
impl<T> Container for Stack<T>
Generic impl; Container::Item becomes concrete T
4
type Item = Vec<f64>;
Matrix implementation uses Vec<f64> as its Item type
5
stack.get(1)
Returns Option<&i32> for Stack, Option<&Vec<f64>> for Matrix