Command 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 this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Command Pattern runs in O(1) time and O(n) space, in Go as in every other language.
- ✓A func value is the command and a slice of them is the queue; a struct with an Execute method is the data form when the command needs fields.
- ✓Define a named interface with a single Execute method taking a context and returning an error, matching the shape the whole ecosystem uses.
- ✓The Go trap: Sending commands into a channel consumed by a worker looks obviously correct and leaks in two ways that tests rarely catch.
- ✓A func value call is indirect and uninlineable, and a closure that captures variables escapes to the heap, so a queue built from closures allocates per command.
What Command Pattern actually is
Command Pattern in Go: what you actually reach for
Go implementation
package command
import (
"context"
"errors"
)
type Command interface {
Execute(ctx context.Context) error
Undo(ctx context.Context) error
}
type SetValue struct {
Store map[string]int
Key string
New, Prev int
HadPrev bool
}
func (c *SetValue) Execute(ctx context.Context) error {
c.Prev, c.HadPrev = c.Store[c.Key], true
c.Store[c.Key] = c.New
return nil
}
func (c *SetValue) Undo(ctx context.Context) error {
if !c.HadPrev {
return errors.New("undo before execute")
}
c.Store[c.Key] = c.Prev
return nil
}
// Producer that cannot leak: every send is guarded by the done channel.
func Feed(ctx context.Context, out chan<- Command, cmds []Command) {
defer close(out) // only the SENDER closes
for _, c := range cmds {
select {
case out <- c:
case <-ctx.Done(): // consumer gone: unwind instead of blocking forever
return
}
}
}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(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Command Pattern?
A func value is the command and a slice of them is the queue; a struct with an Execute method is the data form when the command needs fields. Channels give a concurrent command queue directly, and context.Context is the standard cancellation and deadline mechanism to pass into any command that can block. sync.WaitGroup coordinates completion, and since Go 1.21 the errors.Join function collects failures from a batch of commands into one error.
What is the most common Go mistake when implementing Command Pattern?
Sending commands into a channel consumed by a worker looks obviously correct and leaks in two ways that tests rarely catch. If the consumer returns early, every producer blocked on an unbuffered send stays blocked forever and those goroutines are never collected. If the channel is closed while a producer is still sending, the send panics rather than failing, and the panic happens in the producing goroutine where a recover in the consumer cannot help. A select with a done channel on every send is the standard shape, and only the sender should close.
How does Command Pattern actually perform in Go?
A func value call is indirect and uninlineable, and a closure that captures variables escapes to the heap, so a queue built from closures allocates per command. A slice of structs with a concrete Execute avoids both the allocation and the interface box for a homogeneous queue. Channel operations cost a lock and, when they block, a goroutine park and reschedule; for a purely local command queue a plain slice is significantly faster than a channel and should be the default. Time complexity is O(1) 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 Devin 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.