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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package mainimport "fmt"type Counter struct {count int // unexported - lowercaseTotal 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 exportedc.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