Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Decorator Pattern Implementation in Go

14 min readintermediate
Website QA and SEO audits

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

  • ✓Decorator Pattern runs in O(1) time and O(n) space, in Go as in every other language.
  • ✓Struct embedding gives you the pattern with the least ceremony of any language here: embed an interface value in a struct and every method of that interface is PROMOTED to the outer type automatically, so you write only the methods you actually want to change.
  • ✓Embed the INTERFACE, not a concrete struct, so your decorator accepts any implementation. Override only the methods whose behaviour changes and let promotion forward the rest.
  • ✓The Go trap: Embedding an interface whose value is NIL compiles perfectly and panics at runtime the moment an un-overridden promoted method is called, with a nil-pointer dereference pointing at a line you never wrote, the cost of the convenience.
  • ✓Promoted method calls through an embedded interface are ordinary interface calls, one indirect jump, no allocation, and the compiler can devirtualise and inline them when the concrete type is known at the call site.

What Decorator Pattern actually is

The Decorator pattern adds behaviour to an individual object by wrapping it in another object that implements the same interface and forwards to it, so you can stack capabilities (buffering, then compression, then encryption) without a combinatorial explosion of subclasses. Its defining property is that the decorator is INDISTINGUISHABLE from the thing it decorates at the type level, which is what makes stacking work. Reading about it across these eight languages is unusually confusing for one reason: Python, TypeScript and Swift all have a LANGUAGE feature called a decorator or a wrapper that is related but not the same thing, Python decorators transform functions and classes at definition time, TypeScript has two mutually incompatible decorator systems, and Swift property wrappers decorate storage. Meanwhile Go gets the pattern almost for free through embedding, and Rust has no inheritance to avoid in the first place.

Decorator Pattern in Go: what you actually reach for

Struct embedding gives you the pattern with the least ceremony of any language here: embed an interface value in a struct and every method of that interface is PROMOTED to the outer type automatically, so you write only the methods you actually want to change. The standard library uses this everywhere, bufio.Reader wraps io.Reader, and httptest and middleware chains follow the same shape. http.Handler decoration (a func taking a Handler and returning a Handler) is the canonical Go middleware idiom.

Go implementation

Embed the INTERFACE, not a concrete struct, so your decorator accepts any implementation. Override only the methods whose behaviour changes and let promotion forward the rest. For HTTP, write middleware as func(http.Handler) http.Handler and compose with a small chain helper; that signature is the community standard and interoperates with every router.
go
package store

import (
	"log"
	"net/http"
	"time"
)

type Store interface {
	Get(key string) (string, bool)
	Set(key, value string)
}

// Embedding the INTERFACE promotes every method: override only Get.
type Timed struct {
	Store // nil here compiles and panics at the first promoted call
}

func (t Timed) Get(key string) (string, bool) {
	start := time.Now()
	v, ok := t.Store.Get(key)
	log.Printf("get %s took %s", key, time.Since(start))
	return v, ok
}

// Set is NOT written here, promotion forwards it automatically.

// The canonical Go middleware shape:
func WithLogging(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		next.ServeHTTP(w, r)
		log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start))
	})
}

// Promotion is NOT virtual dispatch: if the embedded Get called Set
// internally, it would call the EMBEDDED Set, never your override.
// Go has no super and no back-dispatch to the outer type.

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 Free

The Go-specific trap

Embedding an interface whose value is NIL compiles perfectly and panics at runtime the moment an un-overridden promoted method is called, with a nil-pointer dereference pointing at a line you never wrote, the cost of the convenience. Second, promotion is NOT virtual dispatch: if a promoted method on the embedded value calls another method of the interface, it calls the EMBEDDED implementation, not your override, because Go has no super and no dynamic dispatch back to the outer type. Wrapping http.ResponseWriter has a specific version of this: your wrapper silently drops the optional http.Flusher and http.Hijacker interfaces unless you re-implement them.

Performance in Go, beyond the O(1)

Promoted method calls through an embedded interface are ordinary interface calls, one indirect jump, no allocation, and the compiler can devirtualise and inline them when the concrete type is known at the call site. Embedding a concrete struct instead of an interface gives fully static dispatch and is free. A decorator chain costs one interface call per layer, which is negligible next to any I/O the chain is wrapping. The asymptotic cost is the same in every language, O(1) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Decorator Pattern between languages.

Real-World Applications

Decorator Pattern is used extensively in production software: framework internals, plugin architectures, state management libraries, and large-scale application architectures all rely on this pattern. In Go, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Decorator Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Decorator Pattern appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Decorator Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Decorator Pattern to build pattern recognition. In Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

Frequently Asked Questions

Which Go type or library should I use for Decorator Pattern?

Struct embedding gives you the pattern with the least ceremony of any language here: embed an interface value in a struct and every method of that interface is PROMOTED to the outer type automatically, so you write only the methods you actually want to change. The standard library uses this everywhere, bufio.Reader wraps io.Reader, and httptest and middleware chains follow the same shape. http.Handler decoration (a func taking a Handler and returning a Handler) is the canonical Go middleware idiom.

What is the most common Go mistake when implementing Decorator Pattern?

Embedding an interface whose value is NIL compiles perfectly and panics at runtime the moment an un-overridden promoted method is called, with a nil-pointer dereference pointing at a line you never wrote, the cost of the convenience. Second, promotion is NOT virtual dispatch: if a promoted method on the embedded value calls another method of the interface, it calls the EMBEDDED implementation, not your override, because Go has no super and no dynamic dispatch back to the outer type. Wrapping http.ResponseWriter has a specific version of this: your wrapper silently drops the optional http.Flusher and http.Hijacker interfaces unless you re-implement them.

How does Decorator Pattern actually perform in Go?

Promoted method calls through an embedded interface are ordinary interface calls, one indirect jump, no allocation, and the compiler can devirtualise and inline them when the concrete type is known at the call site. Embedding a concrete struct instead of an interface gives fully static dispatch and is free. A decorator chain costs one interface call per layer, which is negligible next to any I/O the chain is wrapping. Time complexity is O(1) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

If you are a student, see what GitHub Copilot offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.