Visitor
A visitor walks a closed structure and runs per-node behaviour. In Rust the structure is usually an enum, and the visitor is a match or a trait with one method per variant.
Detailed Explanation
The textbook visitor exists because Java cannot add methods to a closed class hierarchy without editing every class. You double-dispatch: node.accept(visitor) plus visitor.visitBinOp(...). Rust has match. An AST is an enum. A walk is a function that matches and recurses. That is the visitor, and it is the one you should write first.
A trait-shaped visitor appears when several walks share the recursion and differ in the per-node action: type-checking, emitting bytecode, pretty-printing. trait Visit { fn visit_expr(&mut self, e: &Expr); } with a default method that matches and calls itself on children lets each implementor override only the nodes it cares about. The enum stays closed; the walks stay open.
You can invert it: impl Expr { fn walk<V: Visit>(&self, v: &mut V) }. That is closer to accept. It is useful when the recursion is ugly (parent pointers, spans) and you do not want every walk to copy it. It is not useful when you have one walk.
match is exhaustive. Adding a variant breaks every visitor that matches. That is what you want for an AST you control. #[non_exhaustive] on a public AST forces a _ arm and is the escape for libraries that will grow nodes.
When you write a match walk: one or two passes. When you write a Visit trait: three or more passes with shared recursion. When you write double dispatch as in Java: almost never; the enum already is the dispatch.
Keep the walk generic over &Expr unless you are rewriting the tree. A visitor that consumes the AST and rebuilds it is a transform; name it fold or map so readers do not expect a read-only walk. Mixing "visit for side effects" and "rebuild a new tree" in one trait produces methods nobody knows whether to call.
Code Examples
enum Expr {
Num(i64),
Add(Box<Expr>, Box<Expr>),
}
fn eval(e: &Expr) -> i64 {
match e {
Expr::Num(n) => *n,
Expr::Add(a, b) => eval(a) + eval(b),
}
}
fn main() {
let e = Expr::Add(Box::new(Expr::Num(2)), Box::new(Expr::Num(40)));
println!("{}", eval(&e)); // prints: 42
}Common Gotchas
`match` is the default visitor
A trait is extra machinery. Add it when the third walk copies the same recursion.
A public AST without `non_exhaustive` is a compatibility promise
Every new node is a breaking change for downstream `match`es. That may be what you want.
Boxes on recursive variants keep the enum sized
A visitor that takes `Expr` by value will allocate those boxes as it rebuilds. Take `&Expr` unless you are transforming.
Mutable walks need care with children
You cannot mutably visit a child while matching on `&mut parent` without `mem::take` or split borrows. Transform by rebuilding.