rust / intermediate
Snippet
Associated Types in Traits
Associated types allow you to define placeholder types within a trait that implementing types must specify. Unlike generic type parameters, associated types enforce a single concrete type per implementation. This pattern is useful when a trait represents a family of operations where the output type depends on the implementation.
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
trait Operation {type Output;fn execute(&self, value: i32) -> Self::Output;}struct Double;impl Operation for Double {type Output = i64;fn execute(&self, value: i32) -> Self::Output {(value * 2) as i64}}struct AddFive;impl Operation for AddFive {type Output = String;fn execute(&self, value: i32) -> Self::Output {format!("Result: {}", value + 5)}}fn main() {let ops: Vec<Box<dyn Operation<Output = i64>>> = vec![Box::new(Double)];for op in ops {println!("{}", op.execute(10));}}
Breakdown
1
trait Operation {
Defines a trait with an associated type Output
2
type Output;
Placeholder type that implementing structs must specify
3
struct Double;
A concrete implementation that sets Output to i64
4
type Output = i64;
Output type is explicitly i64 for Double implementation
5
struct AddFive;
Different implementation with String as Output type
6
type Output = String;
Different output type per implementation demonstrates flexibility
7
Vec<Box<dyn Operation<Output = i64>>>
Homogeneous collection requires matching Output types