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!
More Related questions...