go / intermediate
Snippet
Composition via Struct Embedding
Go uses struct embedding to achieve composition. When a type is embedded without a field name, its methods and fields are 'promoted' to the outer struct, allowing them to be accessed directly.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package mainimport "fmt"type User struct {ID intName string}func (u User) Greet() {fmt.Printf("Hello, I am %s\n", u.Name)}type Admin struct {User // Embedded fieldLevel int}func main() {a := Admin{User: User{ID: 1, Name: "Alice"},Level: 10,}a.Greet() // Promoted methodfmt.Println("ID:", a.ID) // Promoted field}
Breakdown
1
type Admin struct { User ... }
Embeds the User struct into Admin. This is an anonymous field.
2
a.Greet()
Calls the Greet method from User directly on the Admin instance due to promotion.
3
a.ID
Accesses the ID field of User directly through the Admin instance.