Briefing

Go Embedding Pitfalls: No Virtual Dispatch and Shadowing Issues

ai-dev
by Gabriel Anhaia ·

Replace embedding for behavior that needs overriding with interfaces or explicit dependencies.

What to do now

Replace embedding for behavior that needs overriding with interfaces or explicit dependencies.

Summary

The article discusses how Go’s embedding promotes fields and methods into the outer type’s method set but does not provide virtual dispatch. A common bug occurs when a base handler’s method calls an embedded method, expecting the overridden method in the outer type to execute; instead, the base method runs, leading to silent failures.

The author presents a concrete example where a UserHandler embeds BaseHandler and defines a stricter Validate method. Calling RespondJSON on UserHandler invokes BaseHandler.Validate because the receiver in RespondJSON is a BaseHandler, not a UserHandler, so the stricter validation never runs. The fix is to use an interface for the validator and inject it explicitly, enabling dynamic dispatch.

Another pitfall is shadowing without a super keyword. Go requires explicit calls to the embedded method (e.g., o.Embedded.Foo()), and forgetting to do so can silently omit critical behavior such as tracing. The article emphasizes that Go lacks a super keyword, so developers must be vigilant when overriding methods.

These patterns illustrate that Go’s composition model can lead to subtle bugs if developers assume object‑oriented inheritance semantics.

Key changes

  • Embedding promotes methods but no virtual dispatch
  • RespondJSON calls BaseHandler.Validate, not UserHandler.Validate
  • Interface-based validator enables dynamic dispatch
  • Shadowing requires explicit call to embedded method (e.g., o.Embedded.Foo())
  • Go lacks super keyword, increasing risk of omitted behavior
  • Using interfaces or dependency injection prevents these bugs

Affects

internal

Customer impact

Analyzing matches…

Ask about this story

Impact on an agency? Which customers? Compare historically Risks of waiting