Skip to content
Go

Struct Embedding

Implement composition via embedding.

By EZ4Code Team
structembedding

Code

package main

import "fmt"

type Base struct {
    ID int
}

func (b Base) Describe() string {
    return fmt.Sprintf("Base#%d", b.ID)
}

type User struct {
    Base       // Anonymous embedding
    Name string
    Age  int
}

func main() {
    u := User{
        Base: Base{ID: 1},
        Name: "Alice",
        Age:  30,
    }
    fmt.Println(u.ID)        // Directly access embedded field
    fmt.Println(u.Describe()) // Call embedded method
    fmt.Println(u.Name)
}

Explanation

Go implements code reuse via struct embedding, similar to inheritance but more flexible.

More Go Snippets