Go course

PointersWhen Should You Use Pointers?

Go

Display

Theme

Pointers · Code example

When Should You Use Pointers?

Pointers aren't something you need to use everywhere. Here's a practical guide.

Use a pointer if

  1. A function or method needs to change data that belongs to the caller. This is the most common reason, for example func (k *Keranjang) Tambah(...).
  2. The struct is large and often passed to functions. Copying an address (8 bytes) is cheaper than copying dozens of fields.
  3. You need to tell "not set" apart from the zero value. A Diskon *int field can be nil (not set yet), which is different from 0 (set to zero).
  4. The data has to be shared. For example map[string]*Produk: every part of the program holds the same product, and its fields can be changed directly, gudang["A1"].Stok--, without the copy-change-store pattern.

You don't need a pointer if

  • The type is small and isn't changed: int, bool, a small struct like Titik{X, Y}.
  • The type already behaves like a reference: maps, slices (for changing elements), channels, and functions. A pointer to a map (*map[string]int) is almost never needed.
  • You want the data safe from accidental changes: value semantics means every function works on its own copy.

Returning a pointer from a function is safe

In some languages, returning the address of a local variable is a bug. In Go, it's safe: the compiler moves the variable to the heap when needed (escape analysis).

func ProdukBaru(nama string, harga int) *Produk {
	p := Produk{Nama: nama, Harga: harga}
	return &p // aman
}

Constructor functions named NewXxx or XxxBaru that return a pointer are a very common pattern in Go.

Try it yourself

The editor holds an example of map[string]*Produk and an optional *int field. Run it, then try changing the map type to map[string]Produk and see the compile error that appears on the line gudang["KPI-01"].Stok -= 3.

main.go
package main

import "fmt"

type Produk struct {
	Nama   string
	Harga  int
	Stok   int
	Diskon *int // nil = tidak ada diskon, berbeda dengan diskon 0%
}

func ProdukBaru(nama string, harga, stok int) *Produk {
	p := Produk{Nama: nama, Harga: harga, Stok: stok}
	return &p
}

func (p *Produk) HargaAkhir() int {
	if p.Diskon == nil {
		return p.Harga
	}
	return p.Harga * (100 - *p.Diskon) / 100
}

func main() {
	gudang := map[string]*Produk{
		"KPI-01": ProdukBaru("Kopi Arabika 250g", 65000, 12),
		"TEH-07": ProdukBaru("Teh Melati", 18000, 40),
	}

	// field bisa diubah langsung karena nilai map adalah pointer
	gudang["KPI-01"].Stok -= 3

	diskon := 20
	gudang["TEH-07"].Diskon = &diskon

	for _, kode := range []string{"KPI-01", "TEH-07"} {
		p := gudang[kode]
		fmt.Printf("%s: %s, stok %d, harga Rp%d\n", kode, p.Nama, p.Stok, p.HargaAkhir())
	}
}

Output

Go runtime not loaded yet

Press Run to see what the program prints.

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