Skip to content
Justice Tech School

Struct Embedding

Embed a struct to reuse its fields and methods. It is composition, not inheritance.

Example
package main

import "fmt"

type Animal struct{ Name string }

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

type Dog struct {
	Animal
	Breed string
}

func main() {
	d := Dog{Animal{"Rex"}, "labrador"}
	fmt.Println(d.Name, d.Speak(), d.Breed)
}

Result

Rex Rex makes a sound labrador

Exercise

Reuse fields.

type Dog struct {  }

Quiz Test

Is embedding inheritance?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.