Visitor Pattern Implementation in Go
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 your Design Patterns question into a ready to paste AI prompt, free →
Key Takeaways
- ✓Visitor Pattern runs in O(n) time and O(n) space, in Go as in every other language.
- ✓A type switch over an interface is the Go visitor: switch n := node.(type) with a case per concrete type.
- ✓Use a type switch rather than accept methods, which nobody writes in Go. Include a default case that returns an error naming the unhandled type, since there is no exhaustiveness check.
- ✓The Go trap: A type switch has no exhaustiveness checking, so adding a node type compiles everywhere and falls into default at run time; if default is absent the switch does nothing at all and the traversal silently skips the new node.
- ✓A type switch compiles to a sequence of interface type comparisons, so it is linear in the number of cases and worth ordering by frequency; the compiler uses a hash of the type descriptor for larger switches, which makes it closer to constant.
What Visitor Pattern actually is
Visitor Pattern in Go: what you actually reach for
Go implementation
package expr
import "fmt"
type Node interface{ isNode() }
type Num struct{ Value float64 }
type Add struct{ Left, Right Node }
type Mul struct{ Left, Right Node }
func (Num) isNode() {}
func (Add) isNode() {}
func (Mul) isNode() {}
func Evaluate(n Node) (float64, error) {
switch t := n.(type) {
case Num:
return t.Value, nil
case Add:
l, err := Evaluate(t.Left)
if err != nil { return 0, err }
r, err := Evaluate(t.Right)
if err != nil { return 0, err }
return l + r, nil
case Mul:
l, _ := Evaluate(t.Left)
r, _ := Evaluate(t.Right)
return l * r, nil
default:
// No exhaustiveness check exists: this default is the ONLY safety net.
return 0, fmt.Errorf("unhandled node type %T", n)
}
}
// A nil *Num inside a Node interface still matches 'case *Num' and panics
// on field access, the interface is non-nil even though the pointer is.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 Go-specific trap
Performance in Go, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Visitor Pattern?
A type switch over an interface is the Go visitor: switch n := node.(type) with a case per concrete type. The standard library uses it throughout, and go/ast ships an actual visitor, ast.Visitor with a single Visit method plus ast.Walk and ast.Inspect, which is the canonical example of the pattern in Go. errors.As is a type-switch in disguise for error trees.
What is the most common Go mistake when implementing Visitor Pattern?
A type switch has no exhaustiveness checking, so adding a node type compiles everywhere and falls into default at run time; if default is absent the switch does nothing at all and the traversal silently skips the new node. The subtler trap is that a type switch on an interface holding a NIL pointer of a concrete type still matches that concrete case, because the interface is non-nil, so the case body runs with a nil receiver and panics on the first field access rather than falling through to a nil check.
How does Visitor Pattern actually perform in Go?
A type switch compiles to a sequence of interface type comparisons, so it is linear in the number of cases and worth ordering by frequency; the compiler uses a hash of the type descriptor for larger switches, which makes it closer to constant. Each case that binds the concrete value performs an interface unbox, which is free for pointer types and a copy for value types. Interface dispatch prevents inlining of anything called through the node interface. 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 trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
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.