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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
