Golang / Golang Internals and Memory Management Interview Questions
How does struct embedding work in Go and how does it differ from inheritance?
Go has no class hierarchy or classical inheritance. Instead it supports composition via embedding: embedding a type inside a struct promotes the embedded type's methods and fields to the outer struct. This provides code reuse and satisfies interfaces without the coupling of inheritance.
type Logger struct{ prefix string } func (l Logger) Log(msg string) { fmt.Println(l.prefix+":", msg) } type Server struct { Logger // embedded â methods promoted addr string } s := Server{Logger: Logger{"SERVER"}, addr: ":8080"} s.Log("starting") // promoted â same as s.Logger.Log("starting") s.prefix = "SRV" // promoted field access // Embedding satisfies interfaces type Loggable interface { Log(string) } var l Loggable = s // Server satisfies Loggable via embedded Logger // Method overriding â outer type can shadow embedded method func (s Server) Log(msg string) { fmt.Printf("[%s] %s\n", s.addr, msg) // custom implementation // s.Logger.Log(msg) // explicitly call embedded if needed } // Interface embedding â compose interface contracts type ReadWriter interface { io.Reader // embedded interface io.Writer } // Embedding vs named field type WithName struct { myLogger Logger // named field â NOT promoted, access as s.myLogger.Log() } type WithEmbed struct { Logger // embedded â methods promoted to outer type }
The key difference from inheritance: embedding is purely mechanical code promotion. The embedded type does not know about the outer type and there is no polymorphism between them unless they share an interface. You can embed multiple types (mixins), and method sets are resolved deterministically — if the outer type defines a method with the same name, it shadows the embedded one.
More Related questions...