How to Use Golang Struct Embedding with Code Examples

What is Golang Struct Embedding?

In Golang, you can embed one struct within another. This allows the outer struct to access the fields and methods of the embedded struct, improving code reusability and extensibility.

Basic Embedding

Let’s first examine the basic embedding syntax.

type Parent struct {
    ParentField int
}

type Child struct {
    Parent // Embedding the Parent struct
    ChildField int
}

In the above example, the Child struct embeds the Parent struct, enabling the Child struct to access the fields of the Parent struct.

Code Example 1: Initializing Embedded Structs

c := Child{
    Parent: Parent{
        ParentField: 10,
    },
    ChildField: 20,
}
fmt.Println(c.ParentField) // 10
fmt.Println(c.ChildField)  // 20

Code Example 2: Method Overriding

func (p *Parent) Print() {
    fmt.Println("Parent Method")
}

func (c *Child) Print() {
    fmt.Println("Child Method")
}

c := Child{}
c.Parent.Print() // "Child Method"

Code Example 3: Resolving Field Name Conflicts

type Parent struct {
    Field int
}

type Child struct {
    Parent
    Field int // Conflicting field
}

c := Child{}
c.Parent.Field = 10   // Accessing the Field of Parent
c.Child.Field = 20    // Accessing the Field of Child
fmt.Println(c.Field)  // Child's Field takes precedence

Code Example 4: Embedding Anonymous Structs

type Parent struct {
    Field1 int
}

type Child struct {
    Parent struct {
        Field2 int
    }
    Field3 int
}

c := Child{}
c.Parent.Field1 = 10
c.Parent.Field2 = 20
c.Field3 = 30
fmt.Println(c.Field1) // 10
fmt.Println(c.Field2) // 20
fmt.Println(c.Field3) // 30

Using these code examples, you can better understand the basic concept of struct embedding in Golang and explore how it improves code reusability and maintainability. Struct embedding is one of Go’s powerful features, and by utilizing it effectively, you can write clean and efficient code.

タイトルとURLをコピーしました