Exported vs Unexported
Go has no public or private keywords. Visibility is decided by the first letter of a name:
| Name | Status | Usable from another package? |
|---|---|---|
Hitung, Produk, MaxStok | exported (uppercase) | Yes |
hitung, produk, maxStok | unexported (lowercase) | No, only within the same package |
This rule applies to everything: functions, types, variables, constants, struct fields, and methods.
package akun
type Pengguna struct {
Nama string // exported: bisa dibaca/diubah package lain
kataSandi string // unexported: hanya kode di package akun
}
func Baru(nama, sandi string) Pengguna {
return Pengguna{Nama: nama, kataSandi: sandi}
}
func (p Pengguna) CekSandi(s string) bool { // exported method
return p.kataSandi == s
}
Here Nama can be read and changed by other packages, while kataSandi (the password) is only visible to code in the akun package. From another package:
u := akun.Baru("rina", "rahasia")
fmt.Println(u.Nama) // OK
fmt.Println(u.kataSandi) // error kompilasi: u.kataSandi undefined
fmt.Println(u.CekSandi("rahasia")) // true
This pattern is called encapsulation: sensitive data is hidden, and access goes through functions or methods that you control.
Real effects in the standard library
Many standard packages that work with your structs (through reflection) can also only "see" exported fields. Take encoding/json: json.Marshal only includes exported fields in the JSON it produces.
type Kopi struct {
Nama string
harga int
}
b, _ := json.Marshal(Kopi{Nama: "Latte", harga: 25000})
fmt.Println(string(b)) // {"Nama":"Latte"}
Note: the
json.Marshalexample above is for reading only. The Go runtime in Nibble includes unexported fields when it produces JSON (a runtime limitation), so this exercise doesn't useencoding/json. With Go installed on your own machine, the result is exactly what the comment above shows.
Since the exercises here are a single file (package main), every name can actually be accessed from anywhere in that file. The hidden tests behave like another package: they only use exported functions and methods.
Task
The profile page of a chat app shows a user summary. It turns out the password is showing too! Fix the Profil struct so that:
- the
NamaandKotafields stay exported, - the password field becomes unexported, named
sandi.
Then adjust the code:
buatProfiland theCocokSandimethod use the new field name.- The
Ringkasan()method returns<Nama> dari <Kota>("Name from City") without the password. Example:buatProfil("Rina", "Bandung", "rahasia123").Ringkasan()producesRina dari Bandung. - The
GantiSandi(lama, baru string) boolmethod changes the password and returnstrueonly iflama(the old password) matches the current password andbaru(the new one) isn't empty. Otherwise, the password doesn't change and the result isfalse.
That way, other packages can only check and change the password through methods you control.