Golang / GoLang Basics Interview Questions
How does struct embedding promote methods in Go, and how does it differ from inheritance?
Go uses composition through embedding rather than class inheritance. When a type is embedded (without a field name), its exported methods and fields are promoted to the outer type — they are directly accessible. However, the outer type is NOT a subtype of the embedded type.
type Logger struct{ prefix string }
func (l *Logger) Log(msg string) {
fmt.Printf("[%s] %s\n", l.prefix, msg)
}
// Server embeds Logger — gains the Log method
type Server struct {
*Logger // embedded pointer (promotes Log)
host string
port int
}
srv := Server{
Logger: &Logger{prefix: "SERVER"},
host: "localhost",
port: 8080,
}
srv.Log("starting") // SERVER: starting — promoted method!
srv.Logger.Log("starting") // same thing, explicit call
// Method override — Server can define its own Log
func (s *Server) Log(msg string) {
s.Logger.Log(fmt.Sprintf("%s:%d — %s", s.host, s.port, msg))
}
// KEY: embedding is NOT inheritance
type Describer interface{ Describe() string }
type Base struct{}
func (Base) Describe() string { return "I am Base" }
type Derived struct{ Base }
// Derived satisfies Describer via promotion:
var d Describer = Derived{} // works!
// BUT: you CANNOT use Derived where Base is required
func process(b Base) {}
// process(Derived{}) // COMPILE ERROR — not a subtype!
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...
