Skip to content

Instantly share code, notes, and snippets.

@DougAnderson444
Created March 11, 2025 11:49
Show Gist options
  • Save DougAnderson444/8f42c073e845a8c5d3f256a8750cc924 to your computer and use it in GitHub Desktop.
Save DougAnderson444/8f42c073e845a8c5d3f256a8750cc924 to your computer and use it in GitHub Desktop.
Flexible Rust Options

Trait objects

Use trait objects (&dyn Fn()) when you need runtime polymorphism and don't mind the small performance cost of dynamic dispatch.

Generics

Use generics (F: Fn()) for better performance through static dispatch, but at the cost of potential code bloat due to monomorphization.

Smart Pointer

Use Box<dyn Fn()> when you need to own the function and have runtime polymorphism, but be aware of the heap allocation overhead.

Rust Feature Comparison Table

Feature Trait Objects (&dyn Fn()) Generics (F: Fn()) Smart Pointer (Box<dyn Fn()>)
Type Trait Object Generic Smart Pointer
Runtime/Compile-time Runtime Compile-time Runtime
Use Case When you need runtime polymorphism When you need better performance and can handle code bloat When you need to own the function and have runtime polymorphism
Dispatch ⚠️ Dynamic Dispatch ✅ Static Dispatch ⚠️ Dynamic Dispatch
Performance ⚠️ Small performance cost due to dynamic dispatch ✅ Better performance due to static dispatch ⚠️ Small performance cost due to dynamic dispatch
Code Bloat ✅ No code bloat ⚠️ Potential code bloat due to monomorphization ✅ No code bloat
Ownership ❌ No ownership ❌ No ownership ✅ Ownership
Heap Allocation ✅ No heap allocation ✅ No heap allocation ❌ Heap allocation overhead
Flexibility ❌ Less flexible, requires dyn keyword ⚠️ More flexible, requires generic parameter ❌ Less flexible, requires Box and dyn keywords
Commonalities ⚠️ Provides runtime polymorphism ✅ Provides static dispatch ⚠️ Provides runtime polymorphism
⚠️ Requires dyn keyword ⚠️ Requires generic parameter ⚠️ Requires Box and dyn keywords
Differences ❌ No ownership, no heap allocation ❌ No ownership, no heap allocation ✅ Ownership, heap allocation overhead
⚠️ Small performance cost ✅ Better performance, potential code bloat ⚠️ Small performance cost, heap allocation overhead
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment