Use exported identifiers
Use exported identifiers
An identifier is exported when its first character is a Unicode uppercase letter and it is declared in the package block or is a field or method name. Unexported declarations are accessible within their package, not by selector from another package. Export only the operations consumers need.
Create the files shown below in a fresh directory, then run go run . there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples; modules are covered in detail next.
--- go.mod ---module example.test/lesson
go 1.23
--- main.go ---package main
import ( "example.test/lesson/price" "fmt")
func main() { fmt.Println(price.Total(5)) }
--- price/price.go ---package price
func fee() int { return 2 }func Total(n int) int { return n + fee() }Total is callable from main; fee is an implementation detail. price.fee() would fail compilation in main. A lowercase name is a package access boundary, not a security or encryption mechanism.
Expected output:
7Expose controlled operations
--- go.mod ---module example.test/lesson
go 1.23
--- main.go ---package main
import ( "example.test/lesson/counter" "fmt")
func main() { var c counter.Counter; c.Add(3); fmt.Println(c.Value()) }
--- counter/counter.go ---package counter
type Counter struct{ n int }
func (c *Counter) Add(n int) { if n > 0 { c.n += n }}func (c *Counter) Value() int { return c.n }The field n cannot be set by main; methods mediate changes. The zero value remains usable. Exporting Counter does not export its unexported fields. Package code itself still has access, so keep its invariant checks consistent.
Expected output:
3Try it locally
Create a package label with an unexported prefix function returning "ID:" and an exported Format function that adds it to its string argument. Print Format("7"). Use a fresh module with the same go.mod shown above; run go run .
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Packages and visibility 02: Use exported identifiers
Check the lesson objective before moving on.
Which package-level function is exported?
Can main directly set an unexported field in another package?