🐹 Go (Golang) Intermediate

What is struct embedding in Go?

Answer

Struct embedding is Go's mechanism for composition — embedding one struct inside another to promote its methods and fields without explicit delegation. Declare an embedded field without a name: type Employee struct { Person; Department string }. Now Employee automatically has all of Person's methods and fields accessible directly: emp.Name instead of emp.Person.Name. The embedded type's methods are promoted to the outer type's method set, which is how Go achieves interface satisfaction through composition. The embedded field can still be accessed explicitly by its type name.