Start learning free

LESSON 628 OF 671 · OBJECT-ORIENTED PROGRAMMING

Access Specifiers in Go

Lesson

TL ; DR:

  • Go controls access through identifier capitalization. Lowercase names are unexported (package-private); uppercase names are exported (publicly visible). There are no public/private keywords.


  • Unexported fields are hidden from code outside the package:

    type Dog struct {
        name string   // unexported — hidden outside the package
    }
    
    func NewDog(name string) Dog { return Dog{name: name} }
    func (d Dog) getName() string { return d.name }
    

  • Outside the package, rex.name is a compile error. Use rex.getName() instead.



Full lesson:

Access control in Go uses identifier capitalization instead of explicit access keywords — lowercase identifiers are package-private (unexported), uppercase identifiers are public (exported).


type BankAccount struct {
    balance float64   // unexported — hidden outside the package
}

func (b *BankAccount) deposit(amount float64) {
    if amount < 0 { return }
    b.balance += amount
}
func (b BankAccount) getBalance() float64 { return b.balance }

If balance were exported (written as Balance), any client could just write account.Balance = -1000 and corrupt the state.


Your task

The Dog struct has its name field unexported (lowercase). Add a getName() method that returns name.

Dog's name: Rex
STEP 1 OF 4
    Ctrl + Enter to check