☰ All patterns
Adapter
Make an incompatible type fit the interface you expect.
01
Explain it like I'm new
Real-life analogy
A travel plug adapter
Your laptop charger has a US plug; the wall in India has a different socket. You don't rewire the laptop or the wall. You put a small adapter in between.
😩 The problem
Your app expects Pay(cents int), but a third-party SDK offers MakeTransaction(dollars float64, currency string). You can't edit the SDK.
💡 The pattern
Write a small wrapper type that holds the SDK and implements YOUR interface by translating each call.
02
Walk through the code
Click a step to highlight its lines. This is a complete program you can copy and run.
Press ▶ Run to execute this program.This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.
03
When should I use it?
✅ Reach for it when…
- •Integrating third-party or legacy code.
- •Keeping vendor-specific types out of your core logic.
🚫 Skip it when…
- •You own both sides. Just change the code to match.
🐹 Go tip
Go interfaces are satisfied implicitly, so an adapter is just a struct with the right methods. No 'implements' keyword needed.
🌍 You've already seen it in
http.HandlerFunc adapts a plain function into an http.Handler. io.NopCloser adapts a Reader into a ReadCloser.
04
Quick check
One question. No pressure.
http.HandlerFunc(myFunc) is an example of which pattern?