Go course

PointersNil Pointers

Go

Display

Theme

Pointers · Test exercise

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:

  1. cariAnggota(daftar []Anggota, id int) *Anggota returns a pointer to the element in daftar with a matching ID, or nil if there isn't one.
  2. sapa(a *Anggota) string returns "Halo, <Nama>!", or "Halo, tamu!" ("Hello, guest!") if a is nil.
  3. tambahPoin(daftar []Anggota, id, poin int) bool uses cariAnggota to add to that member's Poin inside the slice. Return false if the member isn't found.
main.go
package main

import "fmt"

type Anggota struct {
	ID   int
	Nama string
	Poin int
}

func cariAnggota(daftar []Anggota, id int) *Anggota {
	// TODO: kembalikan &daftar[i] jika ID cocok, atau nil
	return nil
}

func sapa(a *Anggota) string {
	// TODO: tangani a == nil
	return ""
}

func tambahPoin(daftar []Anggota, id, poin int) bool {
	// TODO: cari anggota, cek nil, lalu tambahkan poin
	return false
}

func main() {
	anggota := []Anggota{
		{ID: 1, Nama: "Dewi", Poin: 20},
		{ID: 7, Nama: "Fajar", Poin: 5},
	}
	fmt.Println(sapa(cariAnggota(anggota, 7)))
	fmt.Println(sapa(cariAnggota(anggota, 99)))
	fmt.Println(tambahPoin(anggota, 1, 15), anggota[0].Poin)
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)