Rust Abstraction Patterns
Files
| File | Content |
|---|---|
generics-pattern.md | Generic parameters, infection chain, meaningful generics |
reuse-patterns.md | Wrapper (composition), trait polymorphism (dispatch), extension traits |
When to Use
- •Composing behaviors (retry, logging, caching)
- •Enhancing existing types without modification
- •Choosing dispatch strategy (enum vs generic vs dyn)
- •Cutting generic infection in deep struct hierarchies
- •Adding methods to foreign types
Prerequisites
- •rust-over-engineering - Abstraction summarizes existing code, not predicts future cases. Start concrete first.
Workflow
- •Adding generics to structs? → Read
generics-pattern.mdfirst - •Enhancing/decorating types? → Use wrapper pattern in
reuse-patterns.md - •Finite polymorphism? → Use enum dispatch
- •Need to cut generic infection? → Enum at appropriate layer
- •Plugin system or heterogeneous collection? →
dyn Traitis acceptable
Priority
| Pattern | Priority | Use Case |
|---|---|---|
| Generic methods | High | Flexible APIs without struct infection |
| Wrapper (Inner) | High | Layer enhancement, decoration |
| Enum dispatch | High | Finite variants, cut infection |
| Extension traits | Medium | Add methods to foreign types |
dyn Trait | Low | Only when static dispatch impossible |
Quick Reference
- •Wrapper:
struct Wrapper<T> { inner: T }- composable, stackable - •Enum dispatch: Known variants, no vtable, cuts infection
- •Generic method:
fn process<T>(&self, arg: T)- no struct infection - •Generic struct:
struct S<T>- infects all layers above, use cautiously