Nil Pointers
The zero value of a pointer type is nil, meaning "points nowhere".
var p *int
fmt.Println(p == nil) // true
Dereferencing a nil pointer makes the program panic:
fmt.Println(*p)
// panic: runtime error: invalid memory address or nil pointer dereference
This is one of the most common runtime errors you'll run into. Preventing it is simple: check for nil before using a pointer that might be empty.
if p != nil {
fmt.Println(*p)
}
Pointers as "a result that might not exist"
Search functions often return a pointer: the address of the data if it's found, nil if it isn't.
type Anggota struct {
ID int
Nama string
Poin int
}
func cari(daftar []Anggota, id int) *Anggota {
for i := range daftar {
if daftar[i].ID == id {
return &daftar[i] // alamat elemen di dalam slice
}
}
return nil
}
Notice &daftar[i], the address of the element inside the slice, not the address of the loop variable. That way the caller can change the original element in the slice:
if a := cari(anggota, 7); a != nil {
a.Poin += 10 // elemen di slice anggota ikut berubah
}
If you write for _, a := range daftar { ... return &a }, what you return is the address of a copy, so the change never reaches the slice.
Methods on a nil receiver
A method with a pointer receiver can still be called on a nil pointer, as long as the method itself doesn't dereference it. This is sometimes used to provide safe default behavior:
func (a *Anggota) NamaTampilan() string {
if a == nil {
return "tamu"
}
return a.Nama
}
Here a nil member gets the display name "tamu" ("guest").
Task
For a library membership system, complete:
cariAnggota(daftar []Anggota, id int) *Anggotareturns a pointer to the element indaftarwith a matchingID, ornilif there isn't one.sapa(a *Anggota) stringreturns"Halo, <Nama>!", or"Halo, tamu!"("Hello, guest!") ifaisnil.tambahPoin(daftar []Anggota, id, poin int) boolusescariAnggotato add to that member'sPoininside the slice. Returnfalseif the member isn't found.