What Is Struct Embedding in Go (Composition Over Inheritance)

Struct embedding in Go enables composition by including one struct inside another, promoting its fields and methods for reuse without inheritance.

Struct embedding in Go is a form of composition where a struct includes another struct as an unexported field, automatically promoting the embedded struct's methods and fields to the outer struct. This allows you to reuse behavior and data without inheritance, creating a "has-a" relationship rather than an "is-a" one.

type Logger struct {
    prefix string
}

func (l *Logger) Log(msg string) {
    fmt.Println(l.prefix + ": " + msg)
}

type Service struct {
    Logger // Embedded struct
    name   string
}

// Service now has a Log method promoted from Logger
func main() {
    s := &Service{Logger: Logger{prefix: "INFO"}, name: "API"}
    s.Log("Started") // Output: INFO: Started
}