Skip to content
Tutorials Center
My learning

Topics

Lesson 114 of 132 ยท Advanced Rust

Design Patterns in Rust

See how classic design patterns look in Rust: strategy with traits and closures, visitor, observer, command with undo and RAII guards, built on ownership.

The classic design patterns were described for languages built around class hierarchies and garbage collection. Rust has neither, so some patterns shrink to a few lines (an enum and a match, a closure), some change shape because of ownership (who owns the listeners in an observer?), and some become automatic (a destructor is the RAII pattern). Knowing how each pattern translates is a good way to review traits, trait objects, closures and Drop in one place.

This lesson walks through five patterns: strategy, visitor, observer, command and RAII guards. For each one you will see the Rust idiom, why ownership shapes it, and when a simpler tool such as a plain enum is the better choice. Builders and type-state patterns are covered separately in Type-State and Builders.

Strategy: swap an algorithm at run time

A strategy is an interchangeable piece of behavior: how a discount is computed, how a list is sorted, how a request is retried. In Rust you have three ways to express it, and the right one depends on how late you decide:

  • Generics (fn checkout<D: Discount>(...)) pick the strategy at compile time. It is monomorphized and can be inlined, with no runtime cost.
  • Trait objects (&dyn Discount or Box<dyn Discount>) pick it at run time, for example from a configuration file, at the price of one pointer call.
  • Closures are strategies without the ceremony. A single-method trait is often just a function in disguise, and you can even implement the trait for every matching closure with a blanket impl, so callers can pass either.
Rust Strategy with traits and closures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Do not build a trait when a closure parameter will do: fn retry(attempts: u32, mut op: impl FnMut() -> bool) is clearer than a RetryStrategy hierarchy. Reach for a trait when the strategy has several methods, needs its own state or deserves a name in your documentation.

Visitor: add operations to a tree without touching it

Imagine a tree of expression nodes. You want to evaluate it, print it and count its nodes, and tomorrow you will want to optimize it. The visitor pattern separates the operations from the data structure: each operation is a type implementing a Visitor trait with one method per node kind, and the nodes only know how to "accept" a visitor and dispatch to the right method.

In a language without enums this is the only way to add operations without editing every node class. Rust has sum types, and an enum plus a match already gives you exactly that: adding a new operation is a new function with a match, and the compiler forces every function to handle new variants. So the first question in Rust is always "do I even need a visitor?". It is worth it when you want to share traversal logic between many passes, when the tree is part of a library and users write their own passes, or when each pass keeps its own state.

classDiagram
    class Expr {
        <<enum>>
        Num
        Add
        Mul
        Neg
        +accept(visitor)
    }
    class Visitor {
        <<trait>>
        +num(n)
        +add(l, r)
        +mul(l, r)
        +neg(e)
    }
    Visitor <|.. Eval
    Visitor <|.. Show
    Visitor <|.. CountNodes
    Expr ..> Visitor : accept calls

Each pass implements Visitor; the enum's accept method dispatches to the matching method.

The visitor below is generic over its result type R, so Eval returns a number, Show returns a String, and CountNodes returns nothing and mutates a counter instead:

Rust A visitor over an expression tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Compare this with the plain approach: fn eval(e: &Expr) -> f64 { match e { ... } }. That is about half the code. Use the visitor when the extra structure pays off; in application code, the match usually wins.

Observer: notify listeners without owning them

An observer lets one object announce events to any number of listeners that it knows nothing about. In languages with shared references this is easy and also a classic source of memory leaks, because the subject and the observer point at each other. In Rust the question is ownership: who owns the listener?

There are three common answers:

  1. The subject owns closures. Vec<Box<dyn FnMut(&Event)>> is the simplest design. A listener that needs shared state captures an Rc<RefCell<...>> (or Arc<Mutex<...>> across threads) by move. Subscribing returns an id so the listener can be removed.
  2. The subject holds Weak references to listener objects owned elsewhere. Dead listeners are skipped and cleaned up on the next publish. This avoids cycles and keeps lifetimes with the listener's owner.
  3. Channels. Each subscriber gets the receiving end of a channel and runs its own loop. No callbacks into foreign code, and it works across threads; see Channels.
Rust An event bus with closure listeners

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice that publish takes &mut self because the listeners are FnMut. A listener that tries to subscribe or unsubscribe during a publish would need a second mutable borrow of the bus, which the compiler (correctly) rejects; the usual fix is to collect requests and apply them after the loop.

Command: operations as values, with undo

A command turns an action into an object: something you can store in a list, replay, send to another thread or reverse. Editors, drawing programs and job queues are built on it. In Rust a command is either an enum (all commands known, easy to serialize and compare) or a Box<dyn Command> (open-ended). The undo stack is then just two Vecs: what has been done and what has been undone.

Ownership helps here. A command that deletes text must remember what it deleted so that undo can restore it, and because apply takes &mut self the command can store that information in itself.

Rust Undo and redo with command objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

If you only need to run commands once (a job queue), Box<dyn FnOnce()> is the whole pattern. The trait is for commands that must be reversed or inspected.

RAII guards: cleanup tied to scope

The most important pattern in Rust needs no boilerplate at all. RAII (resource acquisition is initialization) means a value owns a resource and releases it in its destructor. Files close, locks unlock, memory frees. You can use the same mechanism for your own invariants: a guard is a value whose Drop implementation restores something, no matter how the scope ends (normal return, ?, return or even a panic that unwinds). This is covered in detail in Drop and RAII.

A transaction is a perfect guard: begin, change things, and commit on success; if the guard is dropped without a commit, roll back. Calling commit(self) takes the guard by value, so it cannot be used afterwards, and the compiler enforces that nobody commits twice.

Rust A transaction guard that rolls back on drop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The same shape appears in the standard library: MutexGuard unlocks when dropped, RefCell's Ref and RefMut release their borrow, and JoinHandle-style scope guards wait for threads. When you design an API where "forgetting to clean up" would be a bug, return a guard instead of asking callers to remember a second call.

Rust does not run destructors when a program calls std::process::exit or leaks a value with mem::forget, so a guard protects invariants within a running program, not against a crash of the whole process.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In Rust, when is a plain enum plus match usually better than the visitor pattern?

    A match function is shorter and the compiler checks that it covers every variant. A visitor pays off for shared traversal logic, library extensibility or stateful passes.
  2. 2. What does Vec<Box<dyn FnMut(&Event)>> express in an observer implementation?

    Each Box owns one closure. FnMut means a listener can mutate captured state, which is why publish needs &mut self. Nothing here requires Send or Sync.
  3. 3. Why does Transaction::commit take self by value?

    Taking self moves the guard into commit and drops it there. Any later use is a compile error, so double commits are impossible.
  4. 4. Which tool lets you pick a strategy at run time, for example from a config value?

    Generics are resolved at compile time. A trait object stores the concrete type behind a pointer, so the choice can be made while the program runs.

Summary

  • Strategy: generics for compile-time choice, dyn Trait for run-time choice, closures when a trait would be overkill; a blanket impl lets closures act as strategies.
  • Visitor: operations as types implementing a trait with one method per node kind. A match over an enum is often simpler; use a visitor to share traversal or open the tree to outside passes.
  • Observer: decide who owns the listeners. Box<dyn FnMut> plus Rc<RefCell<..>>, Weak references, or channels all work; avoid reference cycles.
  • Command: actions as values (enum or Box<dyn Command>) that remember what they need to undo; two stacks give undo and redo.
  • RAII guard: a value whose Drop restores an invariant; taking the guard by value in commit makes misuse a compile error.

Next: Project: Guessing Game