乐闻世界logo
搜索文章和话题

How to Embed Structs in Golang?

2月7日 11:02

In Go, embedding a struct is achieved by declaring one struct as a field of another struct without specifying a field name. This embedding makes the internal fields and methods of the embedded struct directly accessible to the outer struct. It is a form of composition that enables Go to achieve behavior similar to inheritance.

For example, if you have a Base struct, you can embed it within another Derived struct:

go
type Base struct { Name string } type Derived struct { Base // Embedding the Base struct Age int }

In this case, the Derived struct automatically inherits all fields and methods of the Base struct. Therefore, you can directly access the Name field through an instance of Derived, as shown below:

go
d := Derived{ Base: Base{Name: "John"}, Age: 30, } fmt.Println(d.Name) // Output: "John"

Thus, the Derived struct instance d can directly access Name, even though it is defined within the Base struct. This approach simplifies relationships between structs and promotes code reuse and extension.

标签:Golang