Strategy 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
- ✓Strategy Pattern runs in O(1) time and O(1) space, in Go as in every other language.
- ✓Func types are first class and named func types are the idiomatic strategy declaration: type Pricing func(cents int) int.
- ✓Declare a named func type rather than repeating the signature, so the intent has a name and godoc has somewhere to hang.
- ✓The Go trap: Before Go 1.22 the loop variable was a single variable reused across iterations, so closures created in a loop all captured the SAME variable and observed its final value; this was the single most reported Go gotcha and it silently produced strategies that all did the same thing.
- ✓Calling through a func value is an indirect call the compiler cannot inline, which is why sort.Slice, driven by a comparator closure and reflection-based swaps, is slower than the generics-based slices.SortFunc introduced in 1.21.
What Strategy Pattern actually is
Strategy Pattern in Go: what you actually reach for
Go implementation
package cart
import "slices"
type Pricing func(cents int) int
func Flat(off int) Pricing { return func(c int) int { return max(0, c-off) } }
func Percent(pct int) Pricing { return func(c int) int { return c * (100 - pct) / 100 } }
type Cart struct{ pricing Pricing }
func (c Cart) Total(cents int) int { return c.pricing(cents) }
// The HandlerFunc adapter: makes a bare func satisfy a one-method interface.
type Pricer interface{ Price(int) int }
func (f Pricing) Price(c int) int { return f(c) } // Pricing now satisfies Pricer
func Sorted(items []int, less func(a, b int) int) {
slices.SortFunc(items, less) // generics: no reflection, unlike sort.Slice
}
// Pre-1.22 (or go.mod below 1.22) every closure here captured the SAME p.
func Build(pcts []int) []Pricing {
out := make([]Pricing, 0, len(pcts))
for _, p := range pcts {
p := p // the classic explicit rebind
out = append(out, Percent(p))
}
return out
}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 Strategy Pattern?
Func types are first class and named func types are the idiomatic strategy declaration: type Pricing func(cents int) int. The standard library takes strategies directly, as in sort.Slice, slices.SortFunc and strings.Map, and it also demonstrates the adapter trick with http.HandlerFunc, a named func type with a method that makes a bare function satisfy the Handler interface. Since Go 1.21 the cmp package supplies cmp.Compare as a ready-made ordering strategy for slices.SortFunc.
What is the most common Go mistake when implementing Strategy Pattern?
Before Go 1.22 the loop variable was a single variable reused across iterations, so closures created in a loop all captured the SAME variable and observed its final value; this was the single most reported Go gotcha and it silently produced strategies that all did the same thing. Go 1.22 changed the semantics so each iteration has its own variable, but the old behaviour still applies to any module whose go directive names a version below 1.22, so the same source file behaves differently depending on a line in go.mod.
How does Strategy Pattern actually perform in Go?
Calling through a func value is an indirect call the compiler cannot inline, which is why sort.Slice, driven by a comparator closure and reflection-based swaps, is slower than the generics-based slices.SortFunc introduced in 1.21. A closure that captures variables allocates a closure object on the heap when it escapes, and passing it to a function that stores it always escapes. Converting a method value such as obj.Method into a func also allocates, because it must box the receiver. Time complexity is O(1) and space is O(1).
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 trialWeighing more options? Compare the best software in each category 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.