Skip to content
GDP for Noobs
☰ All patterns
StructuralBeginner

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.

main.go
1package main
2
3import "fmt"
4
5// PaymentProcessor is what OUR app expects: amounts in cents.
6type PaymentProcessor interface {
7 Pay(amountCents int) string
8}
9
10// ModernPay already fits our interface.
11type ModernPay struct{}
12
13func (ModernPay) Pay(amountCents int) string {
14 return fmt.Sprintf("ModernPay: charged %d cents", amountCents)
15}
16
17// LegacyBankSDK is third-party code we CAN'T change.
18// Different method name, different units (dollars), extra currency arg.
19type LegacyBankSDK struct{}
20
21func (LegacyBankSDK) MakeTransaction(dollars float64, currency string) string {
22 return fmt.Sprintf("LegacyBank: charged %.2f %s", dollars, currency)
23}
24
25// LegacyBankAdapter wraps the SDK and translates our call into its call.
26type LegacyBankAdapter struct {
27 sdk LegacyBankSDK
28}
29
30func (a LegacyBankAdapter) Pay(amountCents int) string {
31 return a.sdk.MakeTransaction(float64(amountCents)/100, "USD")
32}
33
34// Checkout only knows about PaymentProcessor. It never sees the SDK.
35func Checkout(p PaymentProcessor, cents int) {
36 fmt.Println(p.Pay(cents))
37}
38
39func main() {
40 Checkout(ModernPay{}, 1999)
41 Checkout(LegacyBankAdapter{sdk: LegacyBankSDK{}}, 1999)
42}
terminal
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?

Related: Decorator, Facade, Proxy