skip to content
Alvin Lucillo

Access to unexported field via factory func

/ 1 min read

💻 Tech

In Go, structs, struct properties, and functions that don’t start with uppercase character are not exported. This means you will encounter syntax errors when trying to access them from another package.

In the example below, if you try to access user struct from the sample package, you will encounter the error user not exported by package sample. However, if you use a factory function, which is a design pattern that encapsulates the construction of a struct, you can still have a user object but only after construction. Although this is not idiomatic in Go, this is a way to isolate the creation of an object inside the package, so that only the implementation inside the package only exists to create that struct. In other words, it’s a controlled instantiation.

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

// main.go
package main

import (
	"demo/sample"
	"fmt"
)

func main() {
	// user := sample.user{} // error: user not exported by package sample
	fmt.Println(sample.New().Name)
}

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

type user struct {
	Name string
}

func New() user {
	return user{Name: "Francois"}
}