Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

Promoted Fields in Go: How Struct Embedding Works

Embed a struct in Go, access its promoted fields, and handle field name conflicts and struct literals correctly.

Table of Contents

In Go, a struct can embed another type by listing the type without a separate field name. If an embedded struct’s field is unambiguous, Go lets you select it directly on the outer value. This is called a promoted field.

Recommended fields in Golang Picture 1

Embed a struct and access its fields

package main

import "fmt"

type details struct {
    name string
    age  int
}

type student struct {
    details
    year int
}

func main() {
    s := student{
        details: details{name: "Sam", age: 28},
        year:    2025,
    }
    fmt.Println(s.name)         // Sam
    fmt.Println(s.details.age)  // 28
}

s.name is shorthand for s.details.name. The details field still exists. In a keyed literal for student, initialize details explicitly, as shown. You can’t use the promoted name as a top-level key in that literal.

Resolve conflicting names

  • If student declares its own name, s.name selects that field. Use s.details.name to reach the embedded field.
  • If two embedded structs provide the same field at the same depth, a selector like s.name is ambiguous. Name the embedded field in the selector to choose the intended one.
  • If you declare a named field such as info details, its fields aren’t promoted. Use s.info.name.

See the Go specification’s rules for embedded fields for details.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.