Skip to content

Visibility

In Go, visibility is determined by capitalization. Identifiers that start with an uppercase letter are exported (visible outside the package). Lowercase identifiers are unexported (private to the package).

Create a package with both exported and unexported identifiers.

// person.go
package person
type Person struct {
Name string // exported
age int // unexported
}
func New(name string, age int) Person {
return Person{Name: name, age: age}
}
func (p Person) GetAge() int { // exported
return p.age
}
// main.go
package main
import (
"fmt"
"person"
)
func main() {
p := person.New("Alice", 30)
fmt.Println(p.Name) // ok
// fmt.Println(p.age) // error: age not exported
fmt.Println(p.GetAge()) // ok
}
Terminal window
Alice
30