skip to content
Alvin Lucillo

Access to unexported field via embedded struct

/ 2 min read

💻 Tech

In Go, you can’t access an unexported property of a struct from another package; however, if the unexported property is an embedded struct, which has an exported property, that property is promoted to the outer struct.

In the example below, Entity is an exported struct that embeds user, an unexported property. user, has Name as its only exported property. Name becomes accessible from the Entity. However, you can’t set Name during construction of the object. Otherwise, you’ll encounter unknown field Name error, which is demonstrated by the first comment in the example code below. Once that object is created, you can accss Name: entity.Name = "User1".

age, even if it’s part of an embedded struct, is still inaccessible because it starts with a lowercase character. This is demonstrated by the second comment in the example code with the error: type sample.Entity has no field or method age.

Go Playground: https://go.dev/play/p/lpxCXK9U0F7

// -- main.go --
package main

import (
	"demo/sample"
	"fmt"
)

func main() {
	// entity := sample.Entity{Type: "User", Name: "Hello"} // error: unknown field Name in struct literal of type sample.Entity
	entity := sample.Entity{Type: "User"}
	entity.Name = "User1"

	// fmt.Println(entity.age) // entity.age undefined (type sample.Entity has no field or method age)
	fmt.Println(entity.Type, entity.Name)

}

// -- sample/sample.go --
package sample

type Entity struct {
	Type string
	user
}

type user struct {
	Name string
	age  int
}