Strategy via traits
The strategy pattern is a family of interchangeable algorithms. In Rust each strategy is a type that implements a trait, and the context is generic over that trait or stores Box<dyn Trait>.
Detailed Explanation
You have a sorter, a retry policy, a pricing rule. The GoF strategy pattern is an interface plus several classes. In Rust the interface is a trait: trait Retry { fn backoff(&self, attempt: u32) -> Duration; }. Exponential and Fixed implement it. The client is fn run<R: Retry>(retry: R) for static dispatch, or Box<dyn Retry> when the strategy is chosen at runtime and stored.
Static dispatch is the default. Each R gets its own monomorphised run. There is no vtable and the compiler can inline backoff. Runtime selection — a config file says "exponential" — wants dyn Retry. You pay a vtable call and you can keep a Vec<Box<dyn Retry>> if you ever need a list of policies.
This is not inheritance. Strategies do not share a base class of fields. If they share data, they share a struct they contain, or they take the data as arguments. Default trait methods can share behaviour without a parent type.
Closures are a lightweight strategy. fn run(mut backoff: impl FnMut(u32) -> Duration) accepts |n| Duration::from_millis(10 * n) without a named type. Use a trait when the strategy has several methods or you want a name in the public API.
When you reach for a strategy trait: two or more algorithms with the same signature, selected by the caller. When you reach for an enum: a closed set you own and will match. When you reach for a closure: one method, local to the call.
Name strategies for the policy, not the mechanism. ExponentialBackoff is a strategy. Impl1 is not. Put each impl in its own file if the crate is large. Tests should construct the strategy explicitly; a global lazy_static strategy is hidden coupling and makes two tests fight over the default.
Code Examples
trait Greet {
fn greet(&self, name: &str);
}
struct Plain;
struct Loud;
impl Greet for Plain {
fn greet(&self, name: &str) {
println!("hello {name}");
}
}
impl Greet for Loud {
fn greet(&self, name: &str) {
println!("HELLO {}", name.to_uppercase());
}
}
fn run(g: &dyn Greet) {
g.greet("ada");
}
fn main() {
run(&Plain); // prints: hello ada
run(&Loud); // prints: HELLO ADA
}Common Gotchas
An enum is simpler when you own every variant
A trait is for open sets or for hiding the type. Do not invent three traits for three cases in one crate.
`dyn` is a runtime choice
If the strategy is a type parameter in a hot loop, keep it generic.
Closures implement traits you did not name
`Fn` is already a strategy trait. Use it when one method is enough.
Object safety still applies
A strategy method that returns `Self` cannot go through `dyn`. Return a `Box` or keep the API generic.