capypad
0 day streak
go / beginner
Snippet

Exported vs Unexported Identifiers

In Go, visibility is determined by capitalization. Identifiers starting with an uppercase letter are exported (public) and can be accessed from other packages. Those starting with lowercase are unexported (private) and can only be used within the same package. This simple rule replaces keywords like public or private found in other languages.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main
 
import "fmt"
 
type Counter struct {
count int // unexported - lowercase
Total int // exported - uppercase
}
 
func main() {
c := Counter{count: 10, Total: 20}
fmt.Println("Total:", c.Total) // Works
// fmt.Println("count:", c.count) // Error: count not exported
c.Total = 30 // Works
// c.count = 40 // Error: count not exported
}
Breakdown
1
count int
Lowercase identifier - private to this package, cannot be accessed externally
2
Total int
Uppercase identifier - public, accessible from any package that imports this one
3
c.Total = 30
Allowed because Total is exported
4
// c.count = 40 // Error
This would cause a compile error because count is unexported