CodeBlanks Logo Icon CodeBlanks

Struct embedding

Learn to embed one struct inside another.

Struct embedding

Go has no inheritance; instead a struct embeds another struct. The embedded struct's fields and methods become directly accessible through the outer struct:

type Kisi struct {
    Ad  string
    Yas int
}

type Calisan struct {
    Kisi          // no field name: embedded
    Departman string
}

c := Calisan{Kisi{"Ada", 36}, "Ar-Ge"}
fmt.Println(c.Ad, c.Departman)  // Ada Ar-Ge

Composition, not inheritance

Embedding isn't an "is-a" relationship but a "has-a" one: a Calisan can't be used where a Kisi value is expected. If fields share a name, the outer struct's field wins; the embedded one is reached through the full path. This clear rule avoids the complexity of deep inheritance hierarchies.

Practice Employee record

Write Kisi (Ad string, Yas int) and Calisan (Departman string), which embeds it. Create c := Calisan{Kisi{"Ada", 36}, "Ar-Ge"}, do c.Yas++ and print c.Ad, c.Yas and c.Departman.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

type Kisi struct {
    Ad  string
    Yas int
}

type Calisan struct {
    Kisi
    Departman string
}

func main() {
    c := Calisan{Kisi{"Ada", 36}, "Ar-Ge"}
    c.Yas++
    fmt.Println(c.Ad, c.Yas, c.Departman)
}

Expected output

Ada 37 Ar-Ge

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the difference between <code>c.Ad</code> and <code>c.Kisi.Ad</code>?

  • c.Ad returns empty
  • None; c.Ad is shorthand for c.Kisi.Ad Correct answer
  • c.Ad is a copy
  • c.Kisi.Ad doesn't compile

Explanation: Embedded fields are "promoted"; the full path c.Kisi.Ad is always valid too.

2 Embedded field

Question
type Ogretmen struct {
    ____
    Brans string
}
Answer
type Ogretmen struct {
    Kisi
    Brans string
}

Explanation: Writing just the type name, without a field name, embeds the struct.

3 Concept

Term Meaning
Embedding Has-a relationship
c.Ad Promoted field
c.Kisi.Ad Full path
Inheritance Not in Go

All lessons in Beginner