CodeNebula
Go🔧Core Languagebeginner

Embedding

Go · Core Language · Run with go run

Explanation

Go's alternative to inheritance is struct embedding. Embedding a type promotes its methods to the outer struct, allowing composition-based reuse without the complexity of class hierarchies. The embedded type remains accessible by its type name if needed.

Real-World Scenario

A `Logger` struct embeds `io.Writer` and adds a prefix field. Any method on the embedded writer is promoted — `logger.Write(data)` delegates directly to the inner writer.

Quick Snippet

snippet.go
type Animal struct {
    Name string
}
func (a Animal) Speak() string { return a.Name + " makes a sound" }

type Dog struct {
    Animal           // embedded — Dog inherits Speak
    Breed string
}
func (d Dog) Speak() string { return d.Name + " barks" } // override

d := Dog{Animal: Animal{Name: "Rex"}, Breed: "Labrador"}
fmt.Println(d.Speak())       // Rex barks
fmt.Println(d.Animal.Speak()) // Rex makes a sound
fmt.Println(d.Name)           // promoted field access

Full Example

embedding.go
// Compile: go run embedding.go
// Output:
//   Rex barks
//   Rex makes a sound
//   breed: Labrador
package main

import "fmt"

type Animal struct {
	Name string
}

func (a Animal) Speak() string { return a.Name + " makes a sound" }

type Dog struct {
	Animal // embedded — Dog promotes Animal's fields and methods
	Breed  string
}

// Dog overrides Speak
func (d Dog) Speak() string { return d.Name + " barks" }

func main() {
	d := Dog{Animal: Animal{Name: "Rex"}, Breed: "Labrador"}
	fmt.Println(d.Speak())        // overridden method
	fmt.Println(d.Animal.Speak()) // embedded type still reachable
	fmt.Println("breed:", d.Breed)
}
Run command
go run embedding.go