Skip to content

Go Struct Embedding

In Go, embedding is the way we achieve composition. It allows one struct to include another, giving it access to its fields and methods directly.

Basic example

package main

import "fmt"

type base struct {
    num int
}

func (b base) describe() string {
    return fmt.Sprintf("base with num=%v", b.num)
}

type container struct {
    base // This is an embedded struct
    str  string
}

func main() {
    co := container{
        base: base{num: 1},
        str:  "some name",
    }

    // We can access fields of 'base' directly on 'co'
    fmt.Println("co.num:", co.num) // 1

    // We can also call methods of 'base' directly on 'co'
    fmt.Println("describe:", co.describe())
}

Why use Embedding?

  • Code Reuse: Instead of copying fields or methods, you can group them into a base struct and embed it.
  • Polymorphism through Interfaces: If base implements an interface, container will also implement it automatically because it "inherits" the methods.

Important Notes

  • Shadowing: If both structs have a field with the same name, the outer struct's field "shadows" the inner one. You can still access the inner one using the full path (e.g., co.base.num).
  • Not Inheritance: Even though it looks like inheritance, Go uses composition. The base struct doesn't know about the container struct.