Visitor Pattern Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Visitor Pattern runs in O(n) time and O(n) space, in Rust as in every other language.
- ✓An enum plus a match IS the visitor, and it is exhaustive by compiler enforcement, so the pattern in its classical form has no reason to exist for a closed node set.
- ✓Write the enum and match. When you do build a visit trait, give every method a default implementation that recurses, so an implementor overriding one node still traverses the rest; syn and the compiler both do this and it is what makes such visitors usable.
- ✓The Rust trap: The trait-object visitor runs straight into object safety: a visit method that is generic over the node type, or that returns Self, makes the trait unusable as dyn Visitor, and this is discovered only when you try to store the visitor.
- ✓Matching on an enum is a branch on the discriminant with no allocation and no indirection, and the optimiser can inline the whole traversal, so it is the fastest option available.
What Visitor Pattern actually is
Visitor Pattern in Rust: what you actually reach for
Rust implementation
pub enum Node {
Num(f64),
Add(Box<Node>, Box<Node>),
Mul(Box<Node>, Box<Node>),
}
// The enum + match IS the visitor: exhaustive, no allocation, fully inlinable.
pub fn evaluate(n: &Node) -> f64 {
match n {
Node::Num(v) => *v,
Node::Add(l, r) => evaluate(l) + evaluate(r),
Node::Mul(l, r) => evaluate(l) * evaluate(r),
// NO catch-all: adding a variant must break the BUILD.
}
}
// The trait form, shaped like syn's Visit: defaults recurse, so an implementor
// overrides only what it cares about and still traverses everything else.
pub trait Visit {
fn visit_num(&mut self, v: f64) { let _ = v; }
fn visit_add(&mut self, l: &Node, r: &Node) { walk(self, l); walk(self, r); }
fn visit_mul(&mut self, l: &Node, r: &Node) { walk(self, l); walk(self, r); }
}
pub fn walk<V: Visit + ?Sized>(v: &mut V, n: &Node) {
match n {
Node::Num(x) => v.visit_num(*x),
Node::Add(l, r) => v.visit_add(l, r),
Node::Mul(l, r) => v.visit_mul(l, r),
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Visitor Pattern?
An enum plus a match IS the visitor, and it is exhaustive by compiler enforcement, so the pattern in its classical form has no reason to exist for a closed node set. Where a trait-based visitor is genuinely wanted, as in syn, the crate that parses Rust itself, the shape is a Visit trait with one default method per node type plus free walk functions the implementor calls to recurse, which lets an implementor override only the nodes it cares about.
What is the most common Rust mistake when implementing Visitor Pattern?
The trait-object visitor runs straight into object safety: a visit method that is generic over the node type, or that returns Self, makes the trait unusable as dyn Visitor, and this is discovered only when you try to store the visitor. The workaround is a method per concrete node type, which is exactly the expression-problem cost, since adding a node type is then a breaking change to the trait and every implementor. The enum form has the mirror trade: adding a node type breaks every match, which the compiler at least finds for you.
How does Visitor Pattern actually perform in Rust?
Matching on an enum is a branch on the discriminant with no allocation and no indirection, and the optimiser can inline the whole traversal, so it is the fastest option available. A dyn Visitor costs one indirect call per node, which blocks inlining across the visit boundary and is significant on a large tree. Recursion over a deep tree risks a stack overflow exactly as in composite, so a deeply nested expression tree wants an explicit work stack. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.